Svelte

Javascript - Promise 그리고 then 과 여러 상태

올엠 2025. 6. 4. 11:13
반응형

JavaScript의 Promise.then()은 비동기 작업을 처리할 때 매우 중요한 개념입니다. 아래에 개념과 사용법을 정리해드릴게요.

Promise란?

Promise비동기 작업의 최종 완료 또는 실패를 나타내는 객체입니다. 미래에 어떤 값이 반환될 것이라는 "약속"을 의미하죠.

상태 (States)

Promise는 세 가지 상태를 가집니다:

  1. Pending (대기): 아직 결과가 없는 초기 상태
  2. Fulfilled (이행): 작업이 성공적으로 완료됨
  3. Rejected (거부): 작업이 실패함

Promise 생성

const myPromise = new Promise((resolve, reject) => {
  const success = true;

  if (success) {
    resolve("작업 성공!");
  } else {
    reject("작업 실패!");
  }
});
  • resolve(value) → 성공 시 호출
  • reject(error) → 실패 시 호출

.then() 메서드

.then()Promise가 성공했을 때 실행할 콜백 함수를 등록합니다.

myPromise
  .then(result => {
    console.log(result); // "작업 성공!"
  })
  .catch(error => {
    console.error(error); // "작업 실패!"
  });
  • .then()성공 시 실행
  • .catch()실패 시 실행
  • .finally()성공/실패와 관계없이 항상 실행

체이닝 (Chaining)

.then()은 또 다른 Promise를 반환할 수 있어서 연속적인 비동기 작업을 처리할 수 있습니다.

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => {
    console.log("데이터:", data);
  })
  .catch(error => {
    console.error("에러 발생:", error);
  });

예시: 간단한 비동기 함수

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

delay(1000)
  .then(() => {
    console.log("1초 후 실행됨");
    return delay(1000);
  })
  .then(() => {
    console.log("2초 후 실행됨");
  });

 

정리

개념 설명
Promise 비동기 작업의 성공/실패를 나타내는 객체
resolve() 작업 성공 시 호출
reject() 작업 실패 시 호출
.then() 성공 시 실행할 콜백 등록
.catch() 실패 시 실행할 콜백 등록
.finally() 항상 실행되는 콜백 등록

 

반응형