[JavaScript] 비동기
2022.11.23
💡 오늘의 JavaScript 공부
▶️ 비동기
비동기는 음식점에서 실시간으로 여러 주문을 받고 주문 받은 순서와 상관없이 조리가 완료되는 대로 서빙하는 원리와 같다.
쉽게 그림으로 이해하자면
📌 동기
📌 비동기
- 비동기 코드는 순서를 보장하지 않는다.
const printString = (string) => {
setTimeout(function () {
console.log(string);
}, Math.floor(Math.random() * 100) + 1);
};
const printAll = () => {
printString('A');
printString('B');
printString('C');
};
printAll();
console.log(`아래와 같이 비동기 코드는 순서를 보장하지 않습니다!`);
위 코드를 터미널에서 node index.js 를 활용하면 A,B,C | B,C,A | C,A,B 등 랜덤으로 나온다. |
📌 비동기 코드를 동기화 할 수 없는가?
있다. 우선 CallBack 함수를 확인해보자
🕹 Callback
const printString = (string, callback) => {
setTimeout(function () {
console.log(string);
callback();
}, Math.floor(Math.random() * 100) + 1);
};
const printAll = () => {
printString('A', () => {
printString('B', () => {
printString('C', () => {});
});
});
};
printAll();
console.log(
`아래와 같이 Callback 함수를 통해 비동기 코드의 순서를 제어할 수 있습니다!`
);
위 코드를 터미널에서 node index.js로 실행하면 A,B,C 순서대로 나오는 것을 확인할 수 있다.
Callback 함수를 통해 비동기 코드의 순서를 제어할 수 있지만 코드가 길어지고 복잡해질 수 있는데 이러면 가독성이 낮아지는 Callback Hell이 발생한다.
🕹 Callback Hell
이를 막기 위해 Promise라는 함수가 나타나는데
🕹 Promise
const printString = (string) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
console.log(string);
}, Math.floor(Math.random() * 100) + 1);
});
};
const printAll = () => {
printString('A')
.then(() => {
return printString('B');
})
.then(() => {
return printString('C');
});
};
printAll();
console.log(
`아래와 같이 Promise를 통해 비동기 코드의 순서를 제어할 수 있습니다!`
);
다음과 같이 new Promise 와 .then으로 깔끔하게 비동기 함수를 동기화 할 수 있다.
promise를 return으로 해결하지 않으면 promise도 Hell이 발생할 수 있다.
🕹 Promise Hell
( …이런게 있다. 정도만 넘어가고 return으로 잘 해결해 주면 될 것 같다. )
이 복잡한 Promise 코드를 간결하게 작성하도록 Js 에는 async/await 키워드를 제공한다.
🕹 async / await
// 함수 선언식
async function funcDeclarations() {
await 작성하고자 하는 코드
...
}
// 함수 표현식
const funcExpression = async function () {
await 작성하고자 하는 코드
...
}
// 화살표 함수
const ArrowFunc = async () => {
await 작성하고자 하는 코드
...
}
Comments