Promise 객체는 new 키워드와 생성자를 사용해 만듭니다. 생성자는 매개변수로 "실행 함수"를 받습니다. 이 함수는 매개 변수로 두 가지 함수를 받아야 하는데, 첫 번째 함수(resolve)는 비동기 작업을 성공적으로 완료해 결과를 값으로 반활할 때 호출해야 하고, 두 번째 함수(reject)는 작업이 실패하여 오류의 원인을 반화할 때 호출하면 됩니다. 두 번째 함수는 주로 오류 객체를 받습니다.

const myFirstPromise = new Promise((resolve, reject) => {
  // do something asynchronous which eventually calls either
  //
  // resolve(value)           // fulfilled
  // or
  // reject("failure reason") // rejected
});

프로미스는 자바스크립트 비동기 처리에 사용되는 객체입니다.

Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.

function fetchData() {
  return new Promise((resolve, reject) => {
    const success = true;
    if (success) {
      resolve("success");
    } else {
      reject("failure");
    }
  });
}

fetchData()
  .then((result) => {
    console.log(result); // success
  })
  .then((error) => {
    console.log(error);  // undefined
  });

Promise는 다음 중 하나의 상태를 가집니다.

대기(pending): 비동기 처리 로직이 아직 완료되지 않은 상태.

이행(fulfilled): 비동기 처리가 완료되어 프로미스가 결과 값을 반환해준 상태.

거부(rejected): 비동기 처리가 실패하거나 오류가 발생한 상태.

Untitled

대기 중인 프로미스는 값과 함께 이행할 수도, 어떤 이유(오류)로 인해 거부될 수도 있습니다. 이행이나 거부될 때, 프로미스의 then 메서드에 의해 대기열(큐)에 추가된 처리기들이 호출됩니다. 이미 이행했거나 거부된 프로미스에 처리기를 연결해도 호출되므로, 비동기 연산과 처리기 연결 사이에 경합 조건은 없습니다.

myPromise
  .then((result) => {
    console.log(result);                   // resolve
  })
  .catch((error) => {
    console.log(error);                    // reject
  })
  .finally(() => {
    console.log("---all process done---"); // last finally
  });

실제로 비동기 요청 두 개를 보내기

fetch("<https://jsonplaceholder.typicode.com/todos/1>")
  .then((response1) => response1.json())
  .then((json) => console.log(json))
  .then(() => fetch("<https://jsonplaceholder.typicode.com/todos/2>"))
  .then((response2) => response2.json())
  .then((json) => console.log(json))
  .catch((err) => console.log(err))
  .finally(() => console.log("---all process done---"));

// { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
// {
//   userId: 1,
//   id: 2,
//   title: 'quis ut nam facilis et officia qui',
//   completed: false
// }
// ---all process done---

Promise.all()

Promise.all() 메서드는 순회 가능한 객체에 주어진 모든 프로미스가 이행한 후, 혹은 프로미스가 주어지지 않았을 때 이행하는 Promise를 반환합니다. 주어진 프로미스 중 하나가 거부하는 경우, 첫 번째로 거절한 프로미스의 이유를 사용해 자신도 거부합니다.

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 3000, "foo");
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values); // [ 3, 42, 'foo' ]
});

Promise.race()

Promise.race() 메서드는 Promise 객체를 반환합니다. 이 프로미스 객체는 iterable 안에 있는 프로미스 중에 가장 먼저 완료된 것의 결과값으로 그대로 이행하거나 거부합니다.