async/await와 Promise 완전 정리

두부링·2025년 4월 1일

이모저모...

목록 보기
10/12

📌 async/await는 무엇인가?

비동기 작업을 마치 동기처럼 순차적으로 처리할 수 있게 만들어주는 문법!

async function getData() {
  const result = await fetchData(); // fetchData가 끝날 때까지 기다림
  console.log(result); // 결과 출력
}
  • async : 해당 함수가 비동기 함수라는 뜻
  • await : Promise가 처리(resolve) 될 때까지 기다림

왜 필요한가?

기존의 Promise .then() 체인은 이렇게 생겼어:

fetchData()
  .then(res => processData(res))
  .then(final => console.log(final))
  .catch(err => console.error(err));

이걸 async/await를 사용하면 이렇게 변신! 👇

async function main() {
  try {
    const res = await fetchData();
    const final = await processData(res);
    console.log(final);
  } catch (err) {
    console.error(err);
  }
}

→ 가독성 향상! 순서가 눈에 딱 보여!

async/await는 Promise를 처리하는 문법이다!

즉, await는 Promise의 결과(resolve된 값)를 기다렸다가
결과를 변수처럼 다룰 수 있게 해주는 것이야.

const result = await somePromise; ← 이 한 줄이 핵심!

❗ async 함수 바깥은 여전히 비동기다!

console.log("1");

async function fetchSomething() {
  console.log("2");
  await new Promise(res => setTimeout(res, 1000));
  console.log("3");
}

fetchSomething();
console.log("4");

// 출력:
// 1
// 2
// 4
// 3

→ 즉, async 함수 안은 순차적으로 실행되지만,
밖의 코드는 기다려주지 않음! (비동기!)

Promise의 .then()도 흐름을 순서대로 이어주는 역할

doSomething()
  .then(res => {
    console.log("1", res);
    return nextStep(res);
  })
  .then(next => {
    console.log("2", next);
  });
  • .then() 체인도 비동기 결과를 순서대로 처리

  • 그래서 사람들이 "동기처럼 흐름을 탄다"고 표현

  • 하지만 실제로는 콜백 기반 비동기 처리야

결론 요약

✅ 결론 요약

개념설명
Promise비동기 결과를 표현하는 객체
.then()비동기 결과를 받아서 순차적으로 처리
async/awaitPromise를 더 읽기 쉽게 처리하는 문법
awaitPromise가 끝날 때까지 기다린 뒤 결과를 받아옴
밖의 코드여전히 비동기 흐름! await가 멈추지 않음
profile
하이하잉

0개의 댓글