Promise란?

JavaScript에서 Promise는 비동기 작업의 완료 또는 실패를 나타내는 객체
즉, 비동기 작업이 완료되었을 때 그 결과값을 처리할 수 있는 방법을 제공

*비동기 작업: 특정 작업이 완료될 때까지 기다리지 않고 다른 작업을 계속 진행하는 방식


Promise의 기본 구조

Promise는 기본적으로 세 가지 상태를 가짐

  • 대기(pending): 초기 상태, 아직 이행(fulfilled)되거나 거부(rejected)되지 않은 상태
  • 이행(fulfilled): 비동기 작업이 성공적으로 완료된 상태
  • 거부(rejected): 비동기 작업이 실패한 상태


Promise 생성

Promise는 Promise 생성자를 사용하여 생성할 수 있음
생성자는 두 개의 매개변수를 받는 함수를 인자로 받음
이 함수는 비동기 작업을 수행하며, 성공 시 resolve를 호출하고, 실패 시 reject를 호출

const myPromise = new Promise((resolve, reject) => {
    // 비동기 작업을 수행
    const success = true; // 예시로 성공 여부를 설정

    if (success) {
        resolve("작업이 성공적으로 완료되었습니다.");
    } else {
        reject("작업이 실패하였습니다.");
    }
});


Promise 사용하기

Promise를 사용하여 비동기 작업의 결과를 처리할 수 있음
then 메서드는 이행된 경우 호출되며, catch 메서드는 거부된 경우 호출됩니다.

myPromise
    .then(result => {
        console.log(result); // 작업이 성공적으로 완료되었습니다.
    })
    .catch(error => {
        console.error(error); // 작업이 실패하였습니다.
    });


Promise 체이닝

Promise는 체이닝이 가능
즉, 여러 개의 비동기 작업을 순차적으로 처리할 수 있음
then 메서드는 새로운 Promise를 반환하므로, 다음 then 메서드에서 결과를 계속 사용할 수 있음

myPromise
    .then(result => {
        console.log(result);
        return new Promise((resolve) => {
            setTimeout(() => resolve("다음 작업 완료!"), 1000);
        });
    })
    .then(nextResult => {
        console.log(nextResult); // 다음 작업 완료!
    })
    .catch(error => {
        console.error(error);
    });


Promise.all과 Promise.race

  • Promise.all: 여러 개의 Promise를 동시에 실행하고, 모든 Promise가 이행되었을 때 결과를 배열로 반환, 하나라도 거부되면 즉시 거부됨
Promise.all([promise1, promise2])
    .then(results => {
        console.log(results); // 모든 결과를 배열로 반환
    })
    .catch(error => {
        console.error(error); // 하나라도 거부되면 여기에 들어옴
    });
  • Promise.race: 여러 개의 Promise 중 가장 먼저 이행되거나 거부된 Promise의 결과를 반환
Promise.race([promise1, promise2])
    .then(result => {
        console.log(result); // 가장 먼저 완료된 Promise의 결과
    })
    .catch(error => {
        console.error(error); // 가장 먼저 거부된 Promise의 에러
    });