JavaScript

JavaScript 비동기 프로그래밍 - 프로미스

bergerac 2025. 4. 7. 09:11

 Promise란?

Promise는 비동기 작업의 성공 또는 실패를 나타내는 객체입니다.

  • 현재는 알 수 없지만, 미래에 결과가 생기는 **"약속된 값"**을 다루는 방식
  • 콜백 함수보다 가독성이 좋고 에러 처리도 쉬움

Promise의 세 가지 상태

  1. 대기(pending) : 비동기 작업이 아직 끝나지 않은 상태
  2. 이행(fulfilled) : 비동기 작업이 성공적으로 완료되어 결과값을 반환한 상태
  3. 거부(rejected) : 비동기 작업이 실패하여 에러를 반환한 상태

Promise 생성하기

promise는 newPromise()생성자 함수를 통해 만들 수 있다.

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

  if (condition) {
    resolve('프로미스 성공!');
  } else {
    reject('프로미스 실패!');
  }
});
  • resolve(value) → 성공 시 결과값 반환
  • reject(error) → 실패 시 에러 반환

Promise 메서드 체이닝

myPromise
  .then(result => {
    console.log(result); // '프로미스 성공!'
    return '다음 단계';
  })
  .then(nextResult => {
    console.log(nextResult); // '다음 단계'
    return '세 번째 작업';
  })
  .then(thirdResult => {
    console.log(thirdResult); // '세 번째 작업'
  })
  .catch(error => {
    console.log(error); // '프로미스 실패!'
  })
  .finally(() => {
    console.log('무조건 실행'); // 성공/실패 상관없이 실행됨
  });
  • .then() → 성공했을 때 실행할 함수
  • .catch() → 실패했을 때 실행할 함수
  • .finally() → 성공 여부 관계 없이 마지막에 무조건 실행

<서버에서 데이터 가져오기>

1단계 : 데이터 가져오기

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('데이터 가져오기 성공'), 3000);
  });
}

2단계 : 데이터 처리하기

function processData(data) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(`${data} 사용하기`), 3000);
  });
}

3단계: 실행흐름

fetchData()
  .then(result => processData(result))
  .then(processResult => console.log(processResult)) // '데이터 가져오기 성공 사용하기'
  .catch(error => console.error(error));

console.log('메인 로직의 실행 (시간이 많이 걸리지 않는 작업)');

실행 순서

  1. fetchData() 실행 → 3초 대기
  2. console.log('메인 로직의 실행') 즉시 출력
  3. processData() 실행 → 3초 대기
  4. 최종 결과 출력: "데이터 가져오기 성공 사용하기"