Home >Web Front-end >JS Tutorial >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" }));
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"); });
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!