async-await 의 동작 원리 (feat.Generator)

구현 개요

만약 아래와 같이 async 함수를 작성하면

async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

대략 아래와 같이 변환된다.

function fetchData() {
  return new Promise((resolve, reject) => {
    function* generator() {
      try {
        const response = yield fetch('https://api.example.com/data');
        const data = yield response.json();
        resolve(data);
      } catch (error) {
        reject(error);
      }
    }

    const gen = generator();
    function step(nextFn) {
      try {
        const result = nextFn();
        if (result.done) return;
        Promise.resolve(result.value).then(
          (val) => step(() => gen.next(val)),
          (err) => step(() => gen.throw(err))
        );
      } catch (e) {
        reject(e);
      }
    }
    step(() => gen.next());
  });
}

특징