본문 바로가기
Front

[JS] Promise 객체와 async/await

by Ahngyuho 2025. 3. 10.

오늘은 Promise 객체와 async/await에 대해서 알아본 것을 정리해 보려고 합니다.

 

 

1. Promise란?

**Promise(프로미스)**는 비동기 작업의 완료 또는 실패를 나타내는 객체입니다. 비동기 작업이 완료될 때까지 기다릴 필요 없이, 나중에 결과를 받아올 수 있습니다.

Promise의 3가지 상태

  1. Pending (대기 중): 아직 결과가 없는 상태
  2. Fulfilled (이행됨): 비동기 작업이 성공적으로 완료된 상태
  3. Rejected (거부됨): 비동기 작업이 실패한 상태
 
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("데이터 로드 성공!");
  }, 2000);
});

promise.then(result => console.log(result)).catch(error => console.error(error));

 

 

2. async/await란?

async/await는 Promise 기반의 비동기 코드를 더 간결하고 직관적으로 작성할 수 있도록 하는 문법입니다.

async/await의 특징

  • await을 사용하면 비동기 작업이 끝날 때까지 기다릴 수 있음
  • try...catch로 에러를 쉽게 처리할 수 있음
  • then() 체인이 필요 없어 가독성이 뛰어남

async/await 예제

 
async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("데이터 로드 실패:", error);
  }
}

fetchData();

3. Promise와 async/await의 관계

  • async/await은 Promise를 기반으로 동작합니다.
  • async 함수 내부에서 항상 Promise를 반환합니다.
  • await은 Promise가 resolve()를 호출해서 fulfilled 상태가 될 때까지 기다린다는 의미입니다.
  • 결국, async/await은 Promise를 더 직관적으로 사용할 수 있도록 도와주는 문법입니다.

같은 동작을 하는 코드 비교

Promise 사용

fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("데이터 로드 실패:", error));

async/await 사용

 
async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("데이터 로드 실패:", error);
  }
}

fetchData();

4. Fetch API의 단점과 async/await과의 조합

Fetch API는 Promise를 반환하지만, 몇 가지 단점이 있습니다.

Fetch API의 주요 단점

  1. HTTP 에러(404, 500 등)를 자동으로 처리하지 않음
    → response.ok를 직접 확인해야 함
  2. 네트워크 장애 시에도 catch에서 감지되지 않을 수도 있음
    → 예외 처리를 신경 써야 함

해결 방법 (async/await과 함께 사용)

 
async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");

    // HTTP 에러 처리
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("데이터 로드 실패:", error);
  }
}

fetchData();

 

 

5. 언제 Promise를 쓰고 언제 async/await을 쓰면 좋을까?

 

가독성 then() 체인이 길어지면 복잡해짐 직관적이고 간결함
에러 처리 .catch() 사용 try...catch 사용 (더 직관적)
사용 사례 여러 개의 비동기 작업을 동시에 실행할 때 순차적으로 비동기 작업을 실행할 때

비교 예시

Promise 기반 비동기 처리

Promise.all([
  fetch("https://jsonplaceholder.typicode.com/posts").then(res => res.json()),
  fetch("https://jsonplaceholder.typicode.com/users").then(res => res.json())
]).then(([posts, users]) => {
  console.log("Posts:", posts);
  console.log("Users:", users);
}).catch(error => console.error("데이터 로드 실패:", error));

 

async/await 기반 비동기 처리

async function fetchData() {
  try {
    const postsResponse = await fetch("https://jsonplaceholder.typicode.com/posts");
    const usersResponse = await fetch("https://jsonplaceholder.typicode.com/users");

    const posts = await postsResponse.json();
    const users = await usersResponse.json();

    console.log("Posts:", posts);
    console.log("Users:", users);
  } catch (error) {
    console.error("데이터 로드 실패:", error);
  }
}

fetchData();

 

Promise.all()을 사용하면 동시에 여러 요청을 처리할 수 있고, async/await을 사용하면 가독성이 좋아집니다.

 

6. 결론

  • Promise: 비동기 작업을 처리하는 객체. then()과 catch()를 사용하여 체인형으로 처리.
  • async/await: Promise 기반이지만 then() 없이 await을 사용하여 동기적인 코드처럼 작성 가능.
  • Fetch API: 기본적으로 Promise를 반환하므로 async/await과 함께 사용하면 코드가 더 직관적임.
  • Promise vs async/await: 단순한 비동기 요청에는 async/await이 가독성이 좋으며, 여러 개의 요청을 병렬로 처리할 때는 Promise.all()이 유용함.

📌 한 문장 요약

👉 async/await은 Promise의 문법을 더 직관적으로 만든 방식이며, fetch()를 사용할 때 함께 사용하면 더욱 효과적이다! 🚀

'Front' 카테고리의 다른 글

[JS] 프론트에서 서버로 데이터를 전달하는 방법  (0) 2025.03.09