Promise.all()与Promise.allSettled()
这两个Promise的核心区别在于
如果任何 Promise 拒绝,Promise.all()
会立即拒绝,而 Promise.allSettled()
会等待所有 Promise 解决(解决或拒绝),然后返回结果。
Initialize
const promise1 = Promise.resolve('Promise 1 成功');
const promise2 = Promise.reject('Promise 2 失败');
Using Promise.all()
Promise.all([promise1, promise2])
.then((values) => {
console.log(values);
})
.catch((error) => {
console.log('An error occurred in Promise.all():', error);
});
// Output:
// An error occurred in Promise.all(): Promise 2 失败
在上面的代码中,当任何一个 Promise2 拒绝时,Promise.all() 会立即拒绝。
Using Promise.allSettled()
Promise.allSettled([promise1, promise2]).then((results) => {
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(
`Promise ${index + 1} was fulfilled with value:`,
result.value
);
} else {
console.log(
`Promise ${index + 1} was rejected with reason:`,
result.reason
);
}
});
});
// Output:
// Promise 1 was fulfilled with value: Promise 1 成功
// Promise 2 was rejected with reason: Promise 2 失败
在上面的代码中,Promise.allSettled() 等待所有 Promise 解决(解决或拒绝),然后返回结果。