JavaScript/JavaScript,jQuery

[JavaScript] 비동기 처리 - async/await 문법 정리

mingmongs 2025. 6. 23. 12:24

title

이전 글에서는 자바스크립트의 비동기 처리 방식 중 콜백 함수와 Promise를 비교해보았다.
이번 글에서는 Promise를 더 직관적이고 깔끔하게 사용할 수 있는 방법인
async / await 문법에 대해 알아보자.
예시 코드와 함께 실제로 어떻게 사용하는지,
기존 Promise 코드와 어떤 점이 다른지도 함께 정리해보자.

 

1) async / await란?

asyncawait는 ES2017(ES8)에서 도입된 문법으로,
Promise 기반 비동기 코드를 동기식처럼 작성할 수 있도록 도와준다.

  • async 함수는 항상 Promise를 반환한다.
  • await 키워드는 Promise가 처리될 때까지 기다렸다가 결과를 반환한다.

기본 예시

async function fetchData() {
  const result = await getDataFromServer();
  console.log(result);
}

awaitasync 함수 내부에서만 사용 가능하다.

 

2) Promise와 비교해보기

Promise 기반 코드

function fetchData() {
  getDataFromServer()
    .then((result) => {
      console.log("결과:", result);
    })
    .catch((err) => {
      console.error("에러:", err);
    });
}

async / await로 리팩토링

async function fetchData() {
  try {
    const result = await getDataFromServer();
    console.log("결과:", result);
  } catch (err) {
    console.error("에러:", err);
  }
}

비교해보면 async / await는 코드가 더 간결하고 직관적이라는 장점이 있다.

 

3) 여러 비동기 작업 처리하기

순차 실행

async function run() {
  const user = await getUser();
  const profile = await getProfile(user.id);
  const posts = await getPosts(profile.id);
  console.log(posts);
}

병렬 실행 (Promise.all)

async function run() {
  const [user, settings] = await Promise.all([getUser(), getSettings()]);
  console.log(user, settings);
}

여러 비동기 작업을 동시에 실행할 경우에는
Promise.all()을 사용하는 것이 더 효율적이다.

 

4) async / await 정리

항목 Promise async / await
기본 구조 .then(), .catch() try, await, catch
가독성 체이닝 방식 동기식처럼 작성
에러 처리 .catch() 사용 try-catch 문 사용
복잡도 중첩되면 복잡 간결하고 직관적