async
async function 함수명(){
return 1;
}
///////////////////////////////////////////////////////////////
async function 함수명(){
return Promise.resolve(1);
}
async는 항상 promise 객체를 반환한다.
위 코드에서 빗금을 기준으로 위, 아래 코드는 동일하다.
function hello(){
return "hello";
}
anync function helloAsync(){
return "hello abc";
}
helloAsync.then((res) => {
console.log(res);
});
이 코드를 실행하면 hello abc가 출력된다.
function delay(ms){
return new Promise((resolve) => {
setTimeout(resolve,ms); //함수 하나일 때에는 이렇게 함수명만 써도 된다.
})
}
async function helloAsync(){
return delay(3000).then(() =>{
return "hello Async";
});
}
helloAsync().then((res) => {
console.log(res);
});
helloAsync 함수에서 delay의 promise객체를 사용해서 3초를 센 다음, hello Async를 리턴한다. 그려면 여기의 promise는 resolve에 return값을 대입한 것을 수행하니까. 결과적으로 봤을 때, 위 코드는 3초 후 hello async를 출력해주는 함수이다.
await
await를 비동기 함수에 넣으면 이 함수가 마치 동기함수인 것처럼 작동하게된다.(await줄에는 다 동기적으로 수행된다.)
await은 async 함수내에서만 동작한다.
function delay(ms){
return new Promise((resolve) => {
setTimeout(resolve,ms);
})
}
async function helloAsync(){
await delay(3000);
return "hello async";
}
async function main(){
const res = await helloAsync();
console.log(res); // await가 붙어서 바로 hello async 리턴
}
main();
await는 promise에서 resolve한 값을 내놓기 때문에(async함수에서 return 한 값도 resolve한 값으로 간주한다) console.log(res)해도 정상적으로 출력된다.
'Front-end > javascript' 카테고리의 다른 글
[JavaScript] API 호출 (0) | 2023.07.30 |
---|---|
[JavaScript] 콜백지옥과 promise (0) | 2023.07.25 |
[JavaScript] 동기, 비동기 (1) | 2023.07.18 |
[JavaScript] spread 연산자 (0) | 2023.07.17 |
[JavaScript] 비 구조화 할당 (1) | 2023.07.17 |