: 콜백지옥을 해결한 promise에서 더 발전시켜서, 비동기 함수를 동기 함수
처럼 사용할 수 있게 해주기 위해서
function timer (time) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(time);
}, 1000)
})
}
start
time: 10000
time: 20000
time: 30000
end
console.log('start');
timer(1000)
.then(function(time) {
console.log('time: ', time);
return time + 1000;
})
.then(function(time) {
console.log('time: ', time);
return time + 1000;
})
.then(function(time) {
console.log('time: ', time);
return time + 1000;
console.log('end');
})
async function run(time) {
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('time: ', time);
console.log('end');
}
function timer (time) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(time);
}, 1000)
})
}
async function run(time) {
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('time: ', time);
console.log('end');
}
async run(); // 이런식으로 async 함수 앞에 await을 쓸수 있음
https://chat.openai.com/share/dbb25186-6729-45d6-afc7-fdd071927dc0