Home > Web Front-end > JS Tutorial > How Can I Handle Multiple Promises, Including Rejected Ones, in JavaScript?

How Can I Handle Multiple Promises, Including Rejected Ones, in JavaScript?

Susan Sarandon
Release: 2024-12-18 06:07:14
Original
940 people have browsed it

How Can I Handle Multiple Promises, Including Rejected Ones, in JavaScript?

Handling Promises with Mixed Resolutions

In asynchronous programming, dealing with sets of promises can pose challenges. Consider a scenario where you have multiple network requests and one of them is likely to fail. By default, Promise.all() halts the process with an error as soon as one promise rejects. This may not be desirable if you want to capture responses from all the requests.

Pattern without Promise Library

One solution without using a promises library involves wrapping each promise with a "reflect" function. This function returns a new promise that resolves with the value or error from the original promise and includes a "status" property indicating success or rejection.

const reflect = p => p.then(v => ({ v, status: "fulfilled" }),
                            e => ({ e, status: "rejected" }));
Copy after login

You can then map each promise to a reflect promise and call Promise.all() on the mapped array:

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

This approach allows you to handle both successful and rejected promises gracefully.

Built-in Promise.allSettled()

Note that modern browsers and JavaScript environments now have a native Promise.allSettled() method that provides similar functionality. It returns a promise that resolves with an array of results, each representing the status and value (if fulfilled) of the corresponding original promise.

The above is the detailed content of How Can I Handle Multiple Promises, Including Rejected Ones, 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