Promise에 대해서 / Promise.all과 Promise.allSettled의 차이

ex* Promise가 이해되면 위의 이미지가 이해가 된다

Promise의 사용이유

자바스크립트는 동기적 언어이다

그러나 비동기적 함수(API요청)등을 처리하는 경우에는 동작 순서를 보장받지 못한다

보장하기 위해서 Promise등을 사용한다


Promise의 사용구조에 대해서

Promise를 반환받을때 resolve함수등으로 fulfilled등의 상태로 처리된 Promise객체를 받게 된다.

그 Promise객체는 then()에 의해서 처리되거나 await 등을 이용해서 순서를 보장받을수있다


1. Promise를 사용하지 않은 예제 (동작 순서가 보장되지 않음)

function one() {
    console.log("1");
}
function two() {
    setTimeout(function() {
        console.log("2");
    }, 1000);
}
function three() {
    console.log("3");
}

one();
two();
three();

// :결과
// 1
// 3 -> 순서가 이상함
// 2


2. Promise를 사용한 예제 (동작 순서가 보장됨 , 단 then을 사용해야함)

function one() {
    console.log("1");
}
function two() {
    // promise를 반환하도록 변경
    return new Promise(function(resolve){
      setTimeout(function() {
          console.log("2");
          resolve();
      }, 1000);
    });
}
function three() {
    console.log("3");
}

one();
two().then(function(){
  three();
});

// :결과
// 1
// 2 
// 3 -> two의 처리가 끝나고, then으로 반환된 promise를 받아서 three를 호출함


3. Promise를 사용하고 async/await를 사용한 예제 (동작 순서가 보장됨)

function one() {
    console.log("1");
}
function two() {
    // promise를 반환하도록 변경
    return new Promise(function(resolve){
      setTimeout(function() {
          console.log("2");
          resolve();
      }, 1000);
    });
}
function three() {
    console.log("3");
}

// async사용
async function asyncFunction() {
    one();
    await two(); // promise를 반환하는 비동기처리부분에 await사용
    three();
}

asyncFunction();

// :결과
// 1
// 2 
// 3 -> await가 promise의 비동기 처리를 기다린 후 three를 호출함


4. Promise에서 then을 연속으로 사용하는 경우 ( Pending상태의 Promise 객체 )

Promise의 then내부에서 return을 사용시 pending상태의 promise객체를 반환한다 ( Promise이므로 then으로 또 받을수있다 )

그렇게 Promise객체.then().then().. 으로 사용할수 있게 된다

new Promise(function(resolve, reject){
  setTimeout(function() {
    resolve(1);
  }, 2000);
})
.then(function(result) {
  console.log(result); // 1
  return result + 10;
})
.then(function(result) {
  console.log(result); // 11
  return result + 20;
})



5. Promise.all과 Promise.allSettled 의 차이점

Promise.all([promise1,promise2,...])

Promise.all은 비동기 작업을 동시에 처리할수있는 함수이다 ( 병렬처리 )

도중에 하나의 작업이라도 실패(reject)하면 에러처리되며

성공한 비동기 작업을 무시하고 catch로 빠져나와버린다

( 반환형은 배열 )

const promise1 = Promise.resolve(3); // Promise.resolve()를 사용하면 promise의 성공값만 취득할수있다
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

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


Promise.allSettled([promise1,promise2,...])

Promise.all은 비동기 작업을 동시에 처리할수있는 함수이다 ( 병렬처리 )

그러나 도중의 작업이 실패(reject)하더라도

성공한 비동기 작업을 반환하고 종료된다 ( 사용이유 )

( 반환형은 status가 fullfilled(성공) , rejected(실패) 를 가진 배열 )


const promise1 = Promise.resolve('성공');
const promise2 = Promise.reject('실패');

Promise.allSettled([promise1,promise2]).then((results) =>
  console.log(results)
);

// [ { status: "fulfilled", value: "성공" }, { status: "rejected", reason: "실패" }]

eg



참조

Promise참조사이트

자바스크립트 플레이그라운드

Promise의 Pending상태

promise.allsettled참조

Oct 28, 2023 Views 179