자바스크립트 Promise

승민·2025년 5월 12일
1

면접 대비

목록 보기
31/31

Promise는 비동기 작업의 성공 또는 실패 결과를 나중에 사용할 수 있도록 관리하는 객체로, 콜백 지옥을 해결하고 가독성을 높입니다. new Promise((resolve, reject) => {...})로 생성하며, pending, fulfilled, rejected 세 가지 상태를 가집니다. resolve로 성공 값을, reject로 실패 오류를 전달합니다. 후속 처리 메서드(then, catch, finally)로 결과를 처리하며, Promise.all이나 Promise.allSettled로 병렬 작업을 관리합니다.

Promise란?

Promise는 비동기 작업의 결과를 처리하기 위한 객체로, 콜백 함수의 단점(가독성 저하, 에러 처리 어려움, 중첩 문제)을 해결합니다. Promise는 비동기 작업의 상태와 결과를 캡슐화해 흐름을 명확히 관리합니다.

상태
pending: 비동기 작업이 진행 중인 초기 상태.
fulfilled: resolve 호출로 성공한 상태.
rejected: reject 호출로 실패한 상태.

후속 처리 메서드

then(onFulfilled, onRejected): 성공/실패 콜백 처리

promise.then(
  (value) => console.log(value), // "작업 성공!"
  (error) => console.error(error)
);

catch: rejected` 상태일 때 호출

promise.catch((error) => console.error(error)); // "작업 실패"

finally: 성공/실패 여부와 관계없이 실행

promise.finally(() => console.log("작업 완료")); // "작업 완료"

예시

API 호출

fetch("https://api.example.com/data")
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

순차적 비동기 처리

function fetchUser(id) {
  return fetch(`https://api.example.com/users/${id}`).then((res) => res.json());
}

fetchUser(1)
  .then((user) => fetchUser(user.friendId))
  .then((friend) => console.log(friend));

병렬 처리
1. Promise.all: 모든 Promise가 성공해야 결과 반환, 하나라도 실패 시 즉시 rejected

Promise.all([
  fetch("https://api.example.com/data1"),
  fetch("https://api.example.com/data2"),
])
  .then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
  .then(([data1, data2]) => console.log(data1, data2));
  1. Promise.allSettled: 모든 Promise의 성공/실패 결과를 배열로 반환
Promise.allSettled([
  Promise.resolve("성공"),
  Promise.reject(new Error("실패")),
]).then((results) =>
  console.log(results)
  // [{status: "fulfilled", value: "성공"}, {status: "rejected", reason: Error}]
);

장, 단점

장점

  • 가독성
    콜백 지옥 대비 체인 형태로 비동기 흐름을 직관적으로 표현.
  • 에러 처리
    catch로 중앙화된 에러 관리 가능.
  • 유연성
    Promise.all, Promise.race 등으로 복잡한 비동기 작업 제어.

단점

  • 복잡한 에러 처리
    단일 체인에서는 catch로 에러를 쉽게 처리하지만, 중첩 Promise나 다중 비동기 흐름에서는 특정 에러를 구분하기 어려움.
  • 콜백 지옥 미완전 해결
    복잡한 비동기 작업에서 then 체인이 길어지면 가독성이 떨어짐. -> async/await으로 더 간결히 작성 가능

주의점

  • 에러 전파
    catch를 적절히 배치하지 않으면 에러가 무시될 수 있음.
  • 의존성 관리
    Promise.all은 하나라도 실패하면 전체 실패. allSettled로 대체 가능.
  • ESLint
    no-async-promise-executor, promise/catch-or-return 규칙으로 안전한 Promise 사용.

0개의 댓글