Processing Promises Regardless of Failure
When working with a set of Promises that involve network requests, it's often necessary to handle scenarios where some requests may fail. By default, Promise.all() terminates early upon encountering the first rejection. However, in certain situations, you may want to wait until all Promises have completed, even for those that have failed.
Recommended Pattern
One approach is to use the reflect() function, which converts a Promise into a Promise that resolves to a status object with either a fulfilled or rejected property. By mapping the Promises in your array to the reflect() function, you can ensure that all Promises complete, regardless of their status.
const reflect = p => p.then(v => ({ v, status: "fulfilled" }), e => ({ e, status: "rejected" })); Promise.all(arr.map(reflect)).then(results => { const success = results.filter(x => x.status === "fulfilled"); });
In this example, Promise.all() is used with the modified array of Promises, waiting for all of them to complete. The success array will contain the results of the successful Promises, allowing you to handle network failures gracefully and still proceed with actions based on the available data.
Improved Solution (Promise.allSettled)
Built into modern JavaScript is Promise.allSettled, which provides a more concise and efficient way to achieve the desired behavior. It returns a Promise that resolves to an array of results, each containing a fulfilled or rejected status, regardless of the Promise's outcome.
Promise.allSettled([promise]).then(([result]) => { // reach here regardless // { status: "fulfilled", value: 33 } });
The above is the detailed content of How Can I Process All Promises, Even Those That Fail, in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!