aotoyae

[JS] async, await(2) try, catch, Promise.all 본문

JavaScript

[JS] async, await(2) try, catch, Promise.all

aotoyae 2023. 12. 15. 01:53

 

 

복습!

 

❗️ async를 사용하면 then보다 가독성이 좋아진다!

 

asait은 async 함수 내에서만 쓸 수 있다.

일반 함수에서 쓰면 에러 발생

function getName(name) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(name);
    }, 1000);
  });
}

async function showName() {
  const result = await getName("aoto"); // 기다렸다가
  console.log(result); // 넣어준다
}

console.log("시작");
showName(); // 1초 후 "aoto"

 

try { } : 성공 시 실행

catch { } : 실패 시 실행

const f1 = () => {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("1번 주문 완료");
    }, 1000);
  });
};

const f2 = (message) => {
  console.log(message);

  return new Promise((res, rej) => {
    setTimeout(() => {
      res("2번 주문 완료");
      // rej("에러 발생");
    }, 3000);
  });
};

const f3 = (message) => {
  console.log(message);
  return new Promise((res, rej) => {
    setTimeout(function () {
      res("3번 주문 완료");
    }, 2000);
  });
};

console.log("시작");
async function order() {
  try {
    const result1 = await f1();
    const result2 = await f2(result1);
    const result3 = await f3(result2);
    console.log(result3);
  } catch (e) {
    console.log(e); // 3초 후 "에러 발생"
  }
  console.log("종료");
}
order();

// "시작"
// 1초 후 "1번 주문 완료"
// 3초 후 "2번 주문 완료"
// 2초 후 "3번 주문 완료"
// "종료"

 

여기서도 Promise.all을 써보자! (위 코드에서 async 함수 부분만 변경)

console.log("시작");
async function order() {
  try {
    const result = await Promise.all([f1(), f2(), f3()]);
    console.log(result);
  } catch (e) {
    console.log(e); // 3초 후 "에러 발생"
  }
  console.log("종료");
}
order();

// "시작"
// undefined
// undefined
// 3초 후 ['1번 주문 완료', '2번 주문 완료', '3번 주문 완료']
// "종료"

 

 

 

🔗 https://youtu.be/Uh8u20MD978?si=0uFlwlTBbXuph0Az