介绍一下Promise.allSettled
时间: 2023-08-15 11:13:53 浏览: 43
Certainly! `Promise.allSettled` is a method available in JavaScript that allows you to handle multiple promises simultaneously. It takes an iterable (e.g., an array) of promises as input and returns a promise that is fulfilled with an array of promise settlement results.
The settlement results in the returned array contain the status and value (or reason for rejection) of each promise in the input iterable. The status can be either "fulfilled" or "rejected". This method is useful when you need to wait for all promises to settle, regardless of whether they fulfill or reject.
Here's an example usage of `Promise.allSettled`:
```javascript
const promises = [
Promise.resolve('Resolved Promise 1'),
Promise.reject('Rejected Promise 2'),
Promise.resolve('Resolved Promise 3')
];
Promise.allSettled(promises)
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log(`Fulfilled: ${result.value}`);
} else if (result.status === 'rejected') {
console.log(`Rejected: ${result.reason}`);
}
});
});
```
In this example, we have an array of three promises. `Promise.allSettled` is called with the `promises` array, and it returns a new promise. When that promise is fulfilled, the `results` array is logged, indicating the status and value/reason of each promise.
I hope this helps! Let me know if you have any more questions.