JavaScript Promises 초보자를 위한 설명

발행: (2026년 4월 4일 PM 02:46 GMT+9)
5 분 소요
원문: Dev.to

Source: Dev.to

🧠 What Problem Do Promises Solve?

프라미스가 해결하는 문제는 무엇인가?

Before promises, we used callbacks for async tasks:

fetchData(function (data) {
  processData(data, function (result) {
    console.log(result);
  });
});

❌ Callback hell → hard to read, hard to maintain
❌ 콜백 지옥 → 읽기 어렵고, 유지보수가 힘듦

A promise is like a placeholder for a value that may not be available yet.
프라미스는 아직 사용 가능하지 않을 수도 있는 값을 위한 자리표시자와 같습니다.

⏳ Promise States

프라미스 상태

A promise can be in three states:
프라미스는 세 가지 상태를 가질 수 있습니다:

  1. Pending – initial state, waiting for the result
    Pending – 초기 상태, 결과를 기다리는 중
  2. Fulfilled – operation succeeded, value available
    Fulfilled – 작업 성공, 값 사용 가능
  3. Rejected – operation failed, error available
    Rejected – 작업 실패, 오류 사용 가능
Pending → Fulfilled or Rejected

⚙️ Basic Promise Lifecycle

기본 프라미스 라이프사이클

const promise = new Promise((resolve, reject) => {
  const success = true;
  if (success) {
    resolve("Task completed");
  } else {
    reject("Task failed");
  }
});

promise
  .then(result => console.log(result)) // handles success
  .catch(error => console.log(error)); // handles failure

Output if success = true

Task completed

success = true인 경우 출력

Task completed

Output if success = false

Task failed

success = false인 경우 출력

Task failed

🔄 Promise Chaining

프라미스 체이닝

Promises can be chained to run multiple async tasks sequentially:
프라미스를 체인하여 여러 비동기 작업을 순차적으로 실행할 수 있습니다:

fetchData()
  .then(data => processData(data))
  .then(result => console.log(result))
  .catch(err => console.error(err));
  • Cleaner than nested callbacks → 중첩된 콜백보다 깔끔함
  • Easier to read and maintain → 읽기와 유지보수가 더 쉬움

📊 Callback vs Promise

콜백 vs 프라미스

FeatureCallbackPromise
특징콜백프라미스
ReadabilityLow (nested)High (linear)
가독성낮음 (중첩)높음 (선형)
Error handlingHardEasy (catch)
오류 처리어려움쉬움 (catch)
Async flowNestedChained
비동기 흐름중첩체인
Future valueNoYes
미래 값없음있음

🛠️ Real‑World Example

실제 예제

function fetchUser(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (userId === 1) {
        resolve({ id: 1, name: "Rahul" });
      } else {
        reject("User not found");
      }
    }, 1000);
  });
}

fetchUser(1)
  .then(user => console.log(user.name)) // Rahul
  .catch(err => console.log(err));

🧩 Visualizing Promise Lifecycle

프라미스 라이프사이클 시각화

Promise created → pending

(resolve) fulfilled → .then runs
(reject)  rejected → .catch runs
프라미스 생성 → 대기중

(resolve) 이행 → .then 실행
(reject) 거부 → .catch 실행

🧠 Key Takeaways

핵심 정리

  • Promises represent a value in the future.
    프라미스는 미래의 값을 나타냅니다.
  • They prevent callback hell.
    콜백 지옥을 방지합니다.
  • .then() handles success, .catch() handles errors.
    .then()은 성공을 처리하고, .catch()는 오류를 처리합니다.
  • Promises can be chained for sequential async operations.
    프라미스는 순차적인 비동기 작업을 위해 체인될 수 있습니다.

🚀 Final Thoughts

마무리 생각

Promises are the foundation of modern asynchronous JavaScript. Once you master them, you’ll be ready for:

프라미스는 현대 비동기 JavaScript의 기반입니다. 이를 마스터하면 다음을 준비할 수 있습니다:

  • Async/await syntax
    Async/await 구문
  • Complex async workflows
    복잡한 비동기 워크플로
  • Clean, readable, maintainable code
    깔끔하고, 가독성 높으며, 유지보수 가능한 코드
0 조회
Back to Blog

관련 글

더 보기 »

JavaScript에서 this 키워드 이해하기

JavaScript에는 this라는 특수 키워드가 있는데, 초보자들을 자주 혼란스럽게 합니다. 핵심 아이디어는: this는 함수를 “호출하고 있는” 객체를 가리킨다는 것입니다. this는 …

동기 vs 비동기 JavaScript

JavaScript는 single‑threaded이지만, synchronous와 asynchronous 동작을 사용하여 여러 작업을 효율적으로 처리할 수 있습니다. What Is Synchronous Code? Synchronous…

실행 컨텍스트

Execution Context를 주방에 비유해 보세요. 코드를 실행하는 요리를 시작하기 전에 작업 공간, 변수 도구, 그리고 function 레시피가 필요합니다.