본문 바로가기
스터디 열기

async, await

async/await를 사용하면 비동기 코드를 더 쉽게 작성할 수 있습니다. async 키워드는 어떤 함수든 프로미스 객체를 반환하게 만들 수 있습니다. await는 async 함수 안에서 사용되며, Promise가 처리될 때까지 함수의 실행을 일시 중지합니다. 처리가 완료되면 프로미스 객체의 fulfilled 값을 반환합니다.

다음 두 코드는 동일하게 동작합니다. 둘 다 문자열이 아니라 프로미스를 돌려줍니다.

function test() {
  return Promise.resolve('Hello world');
}

console.log(test()); // Promise (이미 이행된 프로미스지만 이 실행 칸에서는 pending으로 보일 수 있습니다)
test().then((value) => console.log(value)); // Hello world
async function test() {
  return 'Hello world';
}

console.log(test()); // Promise (문자열이 아니라 프로미스가 나옵니다. 이 실행 칸에서는 pending으로 보일 수 있습니다)
test().then((value) => console.log(value)); // Hello world

아래 코드에서 await가 어떻게 순서를 만드는지 봅니다.

async function message() {
  const hello = await new Promise((resolve) => {
    setTimeout(() => {
      resolve('hello');
    }, 100);
  });

  const world = await new Promise((resolve) => {
    setTimeout(() => {
      resolve('world');
    }, 100);
  });

  console.log(`${hello} ${world}`);
}

message();

await가 멈추는 것은 프로그램 전체가 아니라 그 async 함수 안의 실행뿐입니다. 함수를 부른 쪽은 기다리지 않고 다음 줄로 넘어갑니다.

async function message() {
  await new Promise((resolve) => setTimeout(resolve, 100));
  console.log('hello world');
}

message();
console.log('message() 다음 줄'); // hello world보다 먼저 출력됩니다

message()를 부른 뒤의 console.log가 먼저 실행되고, 100ms가 지나 hello world가 나옵니다. 09-2에서 본 이벤트 루프와 같은 이야기입니다. 위 순서 그림의 "호출한 쪽은 계속 진행"이 이 장면입니다.

위의 코드를 통해 알 수 있는 await의 중요한 특징은 바로 async 함수 안에서 코드의 실행 순서를 확정 지을 수 있다는 것입니다. 비동기적 코드를 동기적 코드처럼 읽을 수 있어, async를 이용하면 기존의 Promise를 이용하는 것보다 더 가독성 있는 코드를 만들 수 있습니다.

위의 코드를 Promise 만 이용하도록 변경해보면 더 명확해집니다.

function message() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('hello');
    }, 100);
  }).then((hello) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(`${hello} world`);
      }, 100);
    });
  });
}

message().then((text) => console.log(text)); // hello world

만약 async 함수 내에서 오류가 발생하면 어떻게 처리해야할까요? Promise에서 catch 메서드를 사용하여 오류를 처리했던 것처럼 async/await는 오류를 처리하기 위해 try/catch 문을 사용합니다. try 문 안에서 오류가 발생하면 catch 문으로 이동하여 오류를 처리합니다.

async function message() {
  try {
    const hello = await new Promise((resolve) => {
      setTimeout(() => {
        resolve('hello');
      }, 100);
    });

    const world = await new Promise((resolve) => {
      setTimeout(() => {
        resolve('world');
      }, 100);
    });

    console.log(`${hello} ${world}`);
  } catch (error) {
    console.error(error);
  }
}

message();

위 코드는 오류가 나지 않아 catch로 들어가지 않습니다. 실패하는 요청으로 catch에 들어가는 장면을 봅시다. 실습 API에 없는 상품 번호를 요청하면 404가 돌아오고, 10-4에서 배운 대로 response.ok를 확인해 직접 오류를 던집니다.

async function getProduct() {
  try {
    const response = await fetch('https://dev.wenivops.co.kr/services/fastapi-crud/1/product/99999');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    console.log(await response.json()); // 여기까지 오지 않습니다
  } catch (error) {
    console.log('catch로 왔습니다:', error.message); // HTTP error! Status: 404
  }
}

getProduct();

실습 10-4에서 만든 fetch의 then 체인입니다. 같은 일을 하도록 async와 await를 사용해 fetchSuperheroes 함수로 바꿔 보세요.

fetch('https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json')
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

// 여기에 async/await 버전을 작성하세요
풀이 보기

then마다 await를 쓰고, 오류 처리는 try/catch로 합니다.

async function fetchSuperheroes() {
  try {
    const response = await fetch(
      'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json',
    );
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
    return data;
  } catch (error) {
    console.error(error);
  }
}
fetchSuperheroes();

여러 작업을 함께 기다리기: Promise.all

await를 줄줄이 쓰면 앞의 작업이 끝나야 다음 작업이 시작됩니다. 위 message()에서 hello와 world는 서로 상관이 없는데도 100ms씩 차례로 기다렸습니다. 서로 기다릴 필요가 없는 작업은 Promise.all()로 한꺼번에 시작하고 모두 끝날 때까지 함께 기다릴 수 있습니다. 앞 장에서 두 비동기 함수의 결과를 더하지 못했던 문제도 이렇게 풀립니다. 함수가 값을 돌려주는 프로미스를 반환하게 만들면, Promise.all이 두 결과가 모두 준비될 때까지 기다린 뒤 한 번에 줍니다.

function 비동기통신함수1() {
  return new Promise((resolve) => setTimeout(() => resolve(10), 1000));
}

function 비동기통신함수2() {
  return new Promise((resolve) => setTimeout(() => resolve(20), 1000));
}

const [result1, result2] = await Promise.all([비동기통신함수1(), 비동기통신함수2()]);
console.log(result1 + result2); // 30 (약 1초 뒤)

이번에는 서로 기다릴 필요 없는 작업이 얼마나 빨라지는지 봅니다.

const wait = (name, ms) => new Promise((resolve) => setTimeout(() => resolve(name), ms));

async function sequential() {
  const start = Date.now();
  const a = await wait('A', 300);
  const b = await wait('B', 200);
  const c = await wait('C', 100);
  console.log('차례로:', [a, b, c], `${Date.now() - start}ms`);
}

async function together() {
  const start = Date.now();
  const result = await Promise.all([wait('A', 300), wait('B', 200), wait('C', 100)]);
  console.log('함께:', result, `${Date.now() - start}ms`);
}

await sequential(); // 차례로: ['A', 'B', 'C'] 약 600ms
await together(); // 함께: ['A', 'B', 'C'] 약 300ms

서로 기다릴 필요 없는 작업은 Promise.all로 함께 기다리면 가장 긴 작업만큼만 걸린다

가로축은 시작부터 지난 시간이고, 막대 하나가 작업 하나가 진행된 구간입니다. 위의 주황 막대 셋(차례로 await)은 계단처럼 이어져 300 + 200 + 100 = 약 600ms에 끝납니다. 아래 파란 막대 셋(Promise.all)은 모두 0ms에 함께 시작해 가장 긴 A가 끝나는 약 300ms에 모두 끝납니다. 결과 배열의 순서는 끝난 순서가 아니라 넣은 순서(['A', 'B', 'C'])를 지킵니다. 실제 서비스에서 상품 목록과 사용자 정보처럼 서로 상관없는 요청을 동시에 보낼 때 이렇게 씁니다.

Promise.all()은 하나라도 실패하면 바로 실패(catch)로 갑니다. 일부가 실패해도 나머지 결과를 모두 받고 싶다면 Promise.allSettled()를 씁니다.

const wait = (name, ms) => new Promise((resolve) => setTimeout(() => resolve(name), ms));

const results = await Promise.allSettled([wait('A', 100), Promise.reject(new Error('실패'))]);
console.log(results.map((r) => r.status)); // ['fulfilled', 'rejected']

위 예제들처럼 함수 밖 맨 위에서 await를 쓰는 것을 최상위 await(top-level await)라고 합니다. ES2022부터 모듈(<script type="module">)에서 쓸 수 있고, 이 교재 화면의 실행 블록도 맨 위에 await가 있으면 모듈로 실행합니다. 일반 <script>에서는 지금처럼 async 함수 안에서만 쓸 수 있습니다.

마지막 수정