JS | async, await

Chloe K·2022년 7월 13일
0
post-thumbnail

async funciton

  • asyncFunction 객체를 반환하는 하나의 비동기 함수를 정의한다.
  • 암시적으로 Promise를 사용하여 결과를 반환한다.
function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

await 식은 async함수의 실행을 일시 중지하고 전달 된 Promise의 해결을 기다린 다음 async 함수의 실행을 다시 시작하고 완료 후 값을 반환한다.

  • 여러 promise의 동작을 동기스럽게 사용할 수 있게하고, 어떠한 동작을 여러 promise 그룹에서 간단하게 동작하는 것이다.
  • promise가 구조화된 callback과 유사한 것처럼 async/await 또한 제네레이터와 프로미스를 묶는 것과 유사하다.
  • async 함수는 항상 promise 를 반환한다.


async 함수의 오류처리

예제

  async function order() {

    try {
      const result1 = await f1();
      const result2 = await f2(result1);
      const result3 = await f3(result2);
    } catch (e) {
      console.log(e);
    }
  }

  order();
profile
Frontend Developer

0개의 댓글