promise가 많아지면 또 난잡해지기 때문에 깔끔하게 만들 수 있는 방식인 async와 await을 알아보자!
//async & await
//clear style of using promise ;)
//1.async
async function fetchUser() {
//do network request in 10secs...
return 'ellie';
}
const user = fetchUser();
user.then(console.log);
console.log(user);
//함수 앞에 async를 붙혀주면 Promise를 쓴 것과 같은 상태가 된다. 다음은 그대로 결과에 then이나 catch, finally 사용
//2. await
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getApple() {
await delay(3000);
return 'apple';
}
async function getBanana() {
await delay(3000);
return 'banana';
}
//await은 Promise가 실행될 때 까지 기다려주는 것을 나타낸다.
async function pickFruits() {
const apple = await getApple();
const banana = await getBanana();
return `${apple} + ${banana}`
}
//3. useful promise APIs
//Promise.all: 여러가지 함수가 병렬적으로 처리된다.
//Promise.race: 전달값 중 가장 빠른 결과 return