Async / await

Joy·2023년 1월 5일
0

ES6

목록 보기
5/5

async와 await는 promise를 좀 더 간결하고 간편한 코드로 보여지게 한다.
async 와 await는 새로운 것이 아니라 기존에 존재하는 것 위에 간편하게 쓸 수 있는 API를 제공하는 것이다.

  • 사용법
    function 키워드 앞에 async를 붙여주면 된다.
    비동기로 처리되는 부분 앞에 await을 붙여주면 된다.

1. async

async가 붙은 함수는 promise를 반환하고, promise가 아닌 것은 promise로 감싸 반환한다.

// promise로 만든 것
const promise1 = () => new Promise((resolve,reject)=>{
	resolve('ok');
});
// async 사용
const promise1 = async () => {return 'ok'}

promise1().then(result => console.log(result));

2. await

function delay(ms){
    // 정해진 시간 ms가 지나면 resolve를 호출하는 Promise를 리턴
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function getApple(){
    // await은 이 delay가 끝날때까지 기다려준다.  
    await delay(1000);
    return '🍎';
}
async function getBanana(){
    await delay(1000);
    return '🍌';
}

function pickFruits(){
    return getApple().then(apple => {
        return getBanana().then(banana => `${apple} + ${banana}`);
    });
}
// async
async function pickFruits(){
 const apple = await getApple();
 const banana = await getBanana();
 return `${apple} + ${banana}`
}
pickFruits().then((result) => console.log(result));

3. Promise APIs

all
Promise 배열을 전달하여 병렬적으로 다 받을 때까지 모아준다.
getApple와 getBanana는 서로 연관이 없기 때문에 각 3초라는 시간 즉, 총 6초를 기다려야 할 필요가 없다. 이 때, all을 이용하여 병렬로 실행하면 3초만 기다리면 된다.

    function pickAllFruits(){
        return Promise.all([getApple(),getBanana()])
        .then(fruits => fruits.join(' + '));
    }
    pickAllFruits().then(console.log); // 3초뒤 🍎 + 🍌 출력

race
어떤 것이든 상관없이 먼저 리턴되는 첫번째 값만 받아오고 싶을 때

    function pickOnlyOne(){
        return Promise.race([getApple(), getBanana()])
    }
    pickOnlyOne().then(console.log);
profile
🐣

0개의 댓글