[JavaScript] async, await, Promise.all(), Promise.race()

민승기·2023년 11월 5일
0

JavaScript

목록 보기
18/24
post-thumbnail
  • Promise 체이닝을 남발(?) 하다보면 보기 좋지 않은 코드가 생성된다.
promiseSumPrac
    .then((num1) => {
        const result1 = num1 + 50
        return result1;
    })
    .then((num2) => {
        const result2 = num2 + 50
        return result2;
    })
    .then((num3) => {
        const result3 = num3 + 50
        return result3;
    })
    .then((num4) => {
        console.log(num4);  // 250 출력
    })
  • 가독성 또한 떨어지는데 asyncawait를 사용하면 이 문제를 해결할 수 있다.

async

  • 비동기적인 코드를 처리할때 사용한다.
  • promise를 생성하지 않아도 항상 promise를 반환한다.
async function userName() {
    return "seungit";
}

console.log(userName()); // 결과: Promise { 'seungit' }
  • 함수를 호출한 뒤 .then, .catch .finally 를 사용할 수 있다.

await

  • async 함수 내부에서만 사용이 가능하다.
  • 비동기적으로 처리되는 코드 앞에서 사용할 수 있다.
function userName(name) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(name)
        }, 1000);
    });
}

async function sayName() {
    // await 키워드를 사용하여 promise가 처리될때까지 기다림.
    const result = await userName("seungit");
    console.log(result)
}
console.log("너의 이름은?");    // 동기적인 코드
sayName();  // 비동기 함수 호출, 1초 뒤 출력

promise에서 async, await로 바꿔보기

  • 기존 코드
const promiseSumPrac = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(100)
    }, 1000)

});

promiseSumPrac
    .then((num1) => {
        const result1 = num1 + 50
        return result1;
    })
    .then((num2) => {
        const result2 = num2 + 50
        return result2;
    })
    .then((num3) => {
        const result3 = num3 + 50
        return result3;
    })
    .then((num4) => {
        console.log(num4);  // 결과: 250
    })
  • 변경 코드
const promiseSumPrac = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(100)
    }, 1000)

});

async function sum() {
    try {
        const num1 = await promiseSumPrac;
        const result = num1 +50;

        const num2 = result;
        const result2 = num2 + 50;

        const num3 = result2;
        const result3 = num3 +50

        console.log(result3);

    } catch (error) {
        console.log(error);
    }
}
console.log("정답은~~~~~~~?");
sum();	// 결과: 250
  • 예제가 이래서 가독성이 더 좋은지는 모르겠지만 asyncawait를 사용할줄 안다면 callback hell, promise hell에서 벗어날수 있을 것 같다.

  • asyncawait만을 사용하라는 의미는 아니며 필요에 따라 적용해야 할 것이다.

콜백지옥에서 벗어날때 : promise를 사용하자.
가독성을 보완할때 : asyncawait를 사용하자.

병렬처리와 가장 먼저 완료된 데이터 처리

  • 여러개의 비동기적인 작업들을 한번에 즉, 병렬적으로 처리해야 할때가 있을 것이다.
  • 작업 하나하나 기다리면 시간도 오래 걸릴것이다. 이때 활용할 수 있는 것이 Promise.all()이 있다.
  • 그리고 가장 먼저 반환되는 데이터를 확인할때에는 Promise.race()를 사용하면 된다.
  • 두가지의 특징은 배열형태로 전달한다.
function delay(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, ms);
    });
};

async function americano() {
    await delay(2000);
    return "아메리카노"
};

async function cappuccino() {
    await delay(1000);
    return "카푸치노"
};
// 병렬처리
async function allCoffee() {
    return Promise.all([americano(), cappuccino()])
        .then(coffee => coffee.join('와 '));
};

// 먼저 만들어진 커피를 출력하고 싶을때
function firstCoffee() {
    return Promise.race([americano(), cappuccino()]);
};

console.log("커피를 만듭니다.");	// 결과: 커피를 만듭니다. ----- 1번째 출력
allCoffee().then(console.log);	// 결과: 아메리카노와 카푸치노. ----- 3번째 출력 -- 2초만에 출력
firstCoffee().then(console.log);	// 결과: 카푸치노 --- 2번째 출력 -- 1초만에 출력

꾸준하게 다른 예제들을 작성하면서 연습하면 도움이 될 것 같다. 연습 또 연습이다.

profile
개발자를 꿈꾸는 늙은이👨🏻‍💻

0개의 댓글