async--await
코드 블록의 Try it Yourself 버튼으로 직접 실행할 수 있다.
구문
콜백지옥
Info: 비동기적 처리를 할땐 콜백을 활용하게 되는데 하다보면 콜백 함수가 중첩되면서 콜백 지옥에 빠지게 된다.
- 1초후에 일을 하는 timer 함수가 있다
timer(1000, function () {
console.log("작업");
});
- timer 함수에 1초후 콜백함수를 실행시키고 또 콜백을 실행시키게 될경우… 콜백지옥에 빠지게된다
timer(1000, function () {
console.log("작업");
timer(1000, function () {
console.log("작업");
timer(1000, function () {
console.log("작업");
});
});
});
콜백지옥에서 탈출 → promise
Info: 콜백지옥에서 탈출하기 위해서는 promise 객체의 then 을 사용한다.
- .then (함수)
timer(1000)
.then(function () {
console.log("작업");
return timer(1000);
})
.then(function () {
console.log("작업");
return timer(1000);
})
.then(function () {
console.log("작업");
});
- async & await 로 좀더 간단히 작성
async function run(){
await timer(1000)
console.log("작업");
await timer(1000);
console.log("작업");
await timer(1000)
console.log("작업");
}
run();
async & await
Info: then 을 이용하여 콜백을 작성후 async로 변경해본다
- .then (함수)
- timer 함수는 promise 값을 반환하도록 작성되어있다.
- then 함수를 사용하여 1초후 실행을 비동기적으로 여러번 시키는 코드를 작성해보자
function timer(time) {
return new Promise(function (resolve) {
setTimeout(() => {
resolve(time);
}, time);
});
}
console.log('start')
timer(1000)
.then((time) => {
console.log("time:" + time);
return timer(time + 1000);
})
.then((time) => {
console.log("time:" + time);
return timer(time + 1000);
})
.then((time) => {
console.log("time:" + time);
console.log('end')
});

- async & await 로 좀더 간단히 작성
const run = async () => {
console.log("start");
let time = await timer(1000);
console.log("time:" + time);
time = await timer(time + 1000);
console.log("time:" + time);
time = await timer(time + 1000);
console.log("end");
};
run();