// Promise 객체를 리턴하는 함수
function p(ms){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(ms);
}, ms);
});
}
// Promise 객체를 이용해서 비동기 로직을 수행할 때
p(1000).then((ms)=> {
console.log(`${ms}초 후에 실행됨`);
});
이전에 Promise 객체를 then 을 이용해 비동기 로직을 수행할 때 위처럼 했었는데 이것을 await 로 하는 방법을 정리해보자.
(async function main() {
const ms = await p(1000);
console.log(`${ms}초 후에 실행됨`);
})();
await 는 async 함수 안에서만 사용 가능하다.
function p(ms){
return new Promise((resolve, reject) => {
setTimeout(() => {
//resolve(ms);
reject(new Error('reason'));
}, ms);
});
}
(async function main() {
try {
const ms = await p(1000);
//
}catch (error) {
console.log(error);
}
})();
비동기적 처리를 마치 동기적으로 하는 것 처럼 보이게 하여, 코드의 흐름을 파악하기 편하고, 가시성이 좋다.
function p(ms){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(ms);
//reject(new Error('reason'));
}, ms);
});
}
async function asyncF() {
const ms = await p(1000);
return 'Mimi:' + ms;
}
(async function main() {
try {
const name = await asyncF();
console.log(name);
} catch (error) {
console.log(error);
}
})();
asyncF는 p의 인자로 1000을 가지고 가서 setTimeout을 거쳐 resolve가 끝난 후에 asyncF로 돌아와 return mimi를 출력하게 된다.
그래서 여기서는 mimi 가 바로 뜨지않고 1초 뒤에 리턴된다.
function p(ms){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(ms);
//reject(new Error('reason'));
}, ms);
});
}
// Promise
p(1000)
.then(() => p(1000))
.then(() => p(1000))
.then(() => {
console.log('3000 ms 후에 실행');
});
// async await
(async function main() {
await p(1000);
await p(1000);
await p(1000);
console.log('3000 ms 후에 실행');
})();
결과는 둘다 똑같이 3초 뒤에 리턴되는데 async await를 사용하면 비동기 처리가 좀 더 동기적으로 보이게끔 순차적인 로직이 짜인다.
promise.all
promise.race
를 async await로 변경
function p(ms){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(ms);
//reject(new Error('reason'));
}, ms);
});
}
// Promise.all
(async function main() {
const result = await Promise.all([p(1000), p(2000), p(3000)]);
console.log(result);
})();
// Promise.race
(async function main() {
const result = await Promise.race([p(1000), p(2000), p(3000)]);
console.log(result);
})();
promise.all 은 3초 뒤에 모든 값이 배열로 찍히는 반면
promise.race는 제일 먼저 실행된 것만 나온다
그래서 1000초가 먼저 리턴되어 1000이 찍히고 로직은 끝난다.