async
와 await
:
promise를 반환하는 함수(비동기 함수)를 동기적인 함수를 호출한 것처럼 작동하게 하는 키워드
function hello() {
return "hello";
}
async function helloAsync() {
return "hello async";
}
console.log(hello()); // hello
console.log(helloAsync()); // Promise{<pending>}
helloAsync().then((res) => console.log(res)); // hello async
- async 함수 내의 return 값 = 해당 Promise의 resolve의 결과값
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// ms만큼 기다렸다가 resolve를 호출하고 끝나는 비동기 처리 함수
async function helloAsync() {
return delay(3000).then(() => {
return "hello async";
});
}
helloAsync().then((res) => console.log(res));
delay(3000).then(() => { return "hello async"; })
: then 메소드의 결과값 "hello async"✍ await을 써서 가독성 좋게 바꿔보자
async function helloAsync() {
await delay(3000);
return "hello async";
}
helloAsync().then((res) => console.log(res));
// 3초 후 "hello async" 출력
await
을 붙이면 마치 동기적인 함수처럼 작동함await
이 붙은 함수가 끝나기 전까지 다음 코드를 실행하지 않음await
키워드는 async
키워드가 붙은 함수 내에서만 사용 가능async function main() {
const res = await helloAsync();
// res = helloAsync가 실행된 후 return한 값
console.log(res);
}
main();
// 3초 후 "hello async" 출력