Notice
Recent Posts
Recent Comments
«   2025/11   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Today
Total
관리 메뉴

IT CUBE

[JavaScript] 자바스크립트 정리 Part 6 본문

Front-End

[JavaScript] 자바스크립트 정리 Part 6

CUBE 2021. 10. 27. 14:12

 

async & await

Promise를 좀 더 간결하고 동기적으로 실행되는 것처럼 보이게 하는 것

Promise처럼 계속해서 체이닝하면 복잡하기 때문에 이와 같이 사용하는 것

기존에 존재하는 것 위에 감싸서 좀 더 간편하게 API를 사용하는 것을 syntactic sugar라고 부름

무조건 Promise가 나쁘고 async & await를 사용하는 것이 더 좋은 것이 아님

각자 상황에 따라 용도가 다름

 

async

// 함수 앞에 async 붙여주면 자동으로 promise로 실행

async function fetchUser(){
    return 'soo';
}

const user = fetchUser();
user.then(console.log);
console.log(user);

 

await

  • Promise로 구현한 경우

   콜백함수 지옥처럼 보기 좋지 않음

function pickFruits(){
    return getApple()
    .then(apple=>{
        return getBanana()
        .then(banana=>`${apple}+${banana}`);
    });
}

 

  • async와 & await로 구현한 경우

   간결하게 구현 가능

// async 함수안에서만 사용 가능

function delay(ms){
    return new Promise(resolve=>setTimeout(resolve,ms));
}

async function getApple(){
    await delay(1000);
    return 'apple';
}

async function getBanana(){
    await delay(1000);
    return 'banana';
}

async function pickFruits(){
    const apple= await getApple();
    const banana=await getBanana();
    return `${apple} + ${banana}`;
}

pickFruits().then(console.log);
// 2초 후에 실행됨

 

병렬 처리

async function pickFruits(){
    const applePromise=getApple();
    const bananaPromise=getBanana();
    const apple= await applePromise;
    const banana=await bananaPromise;
    return `${apple} + ${banana}`;
} 

pickFruits().then(console.log);
// 1초 후에 실행됨 (각각의 함수를 동시에 가져왔기 때문)

 

유용한 Promise API

function pickAllFruits(){
    return Promise.all([getApple(),getBanana()]) // 배열 형태로 만들어줌
    .then(fruits=>fruits.join(' + '));
}

pickAllFruits().then(console.log);

 

// 먼저 수행되는 것 딱 하나만 호출
// 만약 getApple()이 1초, getBanana()가 2초 후에 호출된다면 getApple()만 호출

function pickOnlyOne(){
    return Promise.race([getApple(),getBanana()]);
}

pickOnlyOne().then(console.log);