- 직관적인 비 동기 처리 코드 작성할 수 있음
- anync
function hello() {
return "hello";
}
async function helloAsync() {
return "hello Async";
}
console.log(hello());
console.log(helloAsync());
//hello
//Promise {<pending>}
//함수에 async를 붙이면 Promise를 반환하는 비동기 처리를 함
helloAsync().then(res) = {
console.log(res);
});
//hello Async
//then을 사용하여 값을 가져올 수 있음
function delay (ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function helloAsync() {
return delay(3000).then(() => {
return "hello Async";
});
}
// 3초 기다렸다가 비동기 통신
helloAsync().then((res) => {
console.log(res);
});
function delay (ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function helloAsync() {
await delay(3000);
return "hello async";
}
// 3초 기다렸다가 비동기 통신
// await은 async 키워드가 붙은 함수에서만 사용가능
// await를 사용한 구문은 동기적으로 실행됨
// 즉, 위에서부터 순서대로 작동하게 됨
async function main () {
const res = await helloAsync();
console.log(res);
}
//hello async
// main 함수를 만들어 그 안에 async / await함수를 넣으면
// 3초를 기다린 후 원하는 값을 띄워줌
// async / await을 활용하여 비동기 코드 Promise를 마치 동기적으로 처리하는 방법을 알아봄
- 결론
- async / await을 활용하여 비동기 코드 Promise를 마치 동기적으로 처리하는 방법을 알아봄
댓글