티스토리 뷰

Promise.all()

여러개의 프로미스가 완료가 된 후 다음로직을 실행해야하는 경우에 사용된다.

이경우 async await보다 합리적인 선택이 될 수 있는데,

아래와 같은 경우 때문이다

// async await을 사용할경우
async asyncAwaitExampleFunc() {
    const resp = await $http.get("/api") // 3초
    const resp2 = await $http.get("/api2") // 5초
    responseHandler(resp, resp2) // 이 함수는 8초후에 실행된다
    ...
}

// Promise.all을 사용할경우
promiseAllExampleFunc() {
    const resp = $http.get("/api") // 3초
    const resp2 = $http.get("/api2") // 5초
    Promise.all([resp, resp2]) 
        .then(resps => ... // promise객체의 response 배열을 들고 5초후에 실행된다
        )
    )
}

위와같은 차이가 발생하는 이유는 Promise.all()에 던져진 Promise객체들이 모두 resolve될때까지 비동기로 작동하기 때문이다. 즉, 위 내용중 promiseAllExampleFunc 함수의 비동기통신은 병렬로 작동한다.

단, Promise.all에는 중요한 특징이 하나가 있는데

Promise.all() 에 인수로 들어간 배열속의 Promise객체중 하나라도 reject가 발생하면 Promise.all() 전체가 즉시 reject된다. 그 즉시 동작은 catch로 넘어가며 전달된 것중 어떤것이 성공이고 실패했는지 알 수 없어, Promise.all은 병렬로 실행시 한가지라도 실패한다면 실패, 전부 성공 했을시에만 성공으로 구분되는 로직에만 사용할 수 있다.

Promise.allSettled()

그래서 사용되는것이 Promise.allSettled이다.

// Promise.allSettled을 사용할경우
promiseAllSettledExampleFunc() {
    const resp = $http.get("/api") // 3초
    const resp2 = $http.get("/api2") // 5초
    Promise.allSettled([resp, resp2]) 
        .then(resps => ... // promise객체의 response 배열을 들고 5초후에 실행된다
        )
    )
}

여기까지만 보면 위내용과 별 다를게 없어보인다.

Promise.allSettled 는 모든 동작이 fullfilled 로 잘 응답되었을때가 아니라 하나라도 reject되었을때 진정으로 빛을 발한다.

// Promise.allSettled을 사용할경우
promiseAllSettledExampleFunc() {
    const resp = $http.get("/api") // 정상응답
    const resp2 = $http.get("/api2") // 오류발생
    Promise.allSettled([resp, resp2]) 
        .then(resps => resps.forEach(result=>{
                console.log(result) // 각 promise객체의 결과값을 찍어본다
            }) 
        )
    )
}

--------------------------------------------------------------------
// console

{ status: "fullfilled", ...}
{ status: "rejected", reason: ... // 에러가 발생한 이유가 여기에 기록된다
    , ...
}

Promise.allSettled는 안정된 메소드로 하나가 실패하더라도 모든 promise들의 결과를 받을 수 있으며 status 값에 따라 잘 분기처리 해주면 된다. 하나가 실패하더라도 다른 값들은 사용해야할 때 사용하면 좋다.

댓글