Home > Web Front-end > JS Tutorial > How Can I Process All Promises, Even Those That Fail, in JavaScript?

How Can I Process All Promises, Even Those That Fail, in JavaScript?

Patricia Arquette
Release: 2024-12-27 14:30:10
Original
221 people have browsed it

How Can I Process All Promises, Even Those That Fail, in JavaScript?

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");
});
Copy after login

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 }
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template