In asynchronous programming, dealing with promises can present challenges when some tasks fail. Let's consider the following scenario:
const arr = [fetch('index.html'), fetch('http://does-not-exist')]; Promise.all(arr) .then(res => console.log('success', res)) .catch(err => console.log('error', err)); // This is executed
The above code makes network requests using fetch. However, since Promise.all will reject upon the first failed request, we encounter an issue: how can we handle the results of all tasks, even those that failed?
To address this problem, we can employ the following native JavaScript techniques:
const reflect = p => p.then(v => ({ v, status: "fulfilled" }), e => ({ e, status: "rejected" }));
This reflect function returns a new promise that resolves to an object containing either the resolved value or the rejection reason, along with a status property indicating the promise's state.
var arr = [fetch('index.html'), fetch('http://does-not-exist')]; Promise.all(arr.map(reflect)).then(function(results){ var success = results.filter(x => x.status === "fulfilled"); });
In this example, we apply reflect to each promise in the array. The resulting array now contains an object with status and error or value properties for each request.
For a modern solution, consider using the built-in Promise.allSettled:
Promise.allSettled([promise]).then(([result]) => { // Code will execute regardless of the promise's state // { status: "fulfilled", value: 33 } });
This method provides a convenient way to handle all settled promises, regardless of their outcome.
By leveraging these techniques, you can gracefully manage asynchronous operations and access the results of all promises, even those that fail, allowing you to make informed decisions based on the available data.
The above is the detailed content of How Can I Handle All Promises, Including Rejected Ones, in Asynchronous JavaScript?. For more information, please follow other related articles on the PHP Chinese website!