Promise.all()
여러개의 Promise 를 비동기적으로 실행한다.
Promise.allSettled
여러개의 Promise 를 비동기적 실행하되 한개의 Promise가 reject 되거나 에러가 발생 되는경우에도 무조건 이행한다.
Promise.all()
fetch, axios 처럼 Promise 처리를 여러번 사용해야하는 경우 Promise.all()
을 사용해서 한번에 처리할수 있다.
async function sampleFunc(): Promise<void> {
// time start
console.time('promise all example');
// first promise
const fetchNameList = async (): Promise<string[]> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result: any = ['Jack', 'Joe', 'Beck'];
resolve(result);
}, 300);
});
};
// second promise
const fetchFruits = async (): Promise<string[]> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result: any = ['Apple', 'Orange', 'Banana'];
resolve(result);
}, 200);
});
};
// third promise
const fetchTechCompanies = async (): Promise<string[]> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result: any = ['Apple', 'Google', 'Amazon'];
resolve(result);
}, 400);
});
};
// promise all
const result: any[] = await Promise.all([
fetchNameList(),
fetchFruits(),
fetchTechCompanies(),
]);
// time end
console.timeEnd('promise all example');
console.log('%j', result);
}
// execute
sampleFunc();
‼️ 위의 예시코드 중 1개라도 reject 되거나 에러가 발생할 경우 모든 Promise 가 reject 된다.
Promise.allSettled()
실행은 Promise.all()
과 동일한 형태로 실행을 하지만
배열로 받은 모든 프로미스의 reject 여부와 상관없이, 전부 완료만 되었다면 해당 프로미스들의 결과를 배열로 리턴한다.
const promise1 = new Promise((resolve) => {
setTimeout(() => {
resolve(1);
}, 3000);
});
const promise2 = new Promise((resolve) => {
setTimeout(() => {
resolve(2);
}, 2000);
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('에러 발생'));
}, 2500);
});
Promise.allSettled([promise1, promise2, promise3])
.then((result) => console.log(result))
.catch((e) => console.error(e));
Promise.all
보다 무조건적으로 Promise.allSettled()
의 기능이 더 좋다 이런것이 아니기 때문에 적절한 판단으로 적재적소에 사용하는게 좋다