async/await이 promise보다 좋은 이유

yonghee·2022년 1월 25일
0

꼭 알아두자

목록 보기
4/8

Async/await

asnyc/await 는 비동기 코드를 작성하는 새로운 방법이다. 이전에는 비동기코드를 작성하기 위해 callback이나 promise를 사용해야 했다. async/await 는 실제로는 최상위에 위치한 promise에 대해서 사용하게 된다. async/await는 promise처럼 non-blocking 이다.

  • 코드가 간결해지고, 가독성이 높아진다.
  • 응답데이터로 들어오는 변수(관례적으로 많이 사용되는 data, response)를 없앨 수 있다.
  • try / catch로 에러를 핸들링할 수 있다.
  • error가 어디서 발생했는지 알기 쉽다.
  • 디버깅의 수월함 async/await를 사용하면 디버깅이 훨씬 수월해 진다.
// promise 연속 호출
function getData() {
  return promise1()
      .then(response => {
          return response;
      })
      .then(response2 => {
          return response2;
      })
      .catch(err => {
          //TODO: error handling
          // 에러가 어디서 발생했는지 알기 어렵다.
      });
}

// async / await 연속 호출
async function getData() {
  const response = await promise1();
  const response2 = await promise2(response);
  return response2;
}
profile
필요할 때 남기는 날것의 기록 공간

0개의 댓글