Waiting for All Promises, Regardless of Failure
In scenarios where you have a series of promises making network requests that may encounter failures, you might prefer to wait for all promises to complete before proceeding, even if some fail.
The built-in Promise.allSettled method provides a straightforward solution:
Promise.allSettled([promise]).then(([result]) => { // Reached regardless of outcome // {status: "fulfilled", value: 33} });
Prior to the introduction of Promise.allSettled, you could use a reflect function to achieve the same result:
const reflect = (p) => p.then( (v) => ({ v, status: "fulfilled" }), (e) => ({ e, status: "rejected" }) ); reflect(promise).then((v) => { console.log(v.status); });
Alternatively, extending the reflect function to work with an array of promises:
function reflect(promises) { return Promise.all(promises.map((p) => { return p.then((v) => ({ v: v, status: "fulfilled" }), (e) => ({ e: e, status: "rejected" })); })); } reflect(promises).then((results) => { var success = results.filter((x) => x.status === "fulfilled"); });
By utilizing these techniques, you can gracefully handle network failures and ensure that your code continues to execute as intended, regardless of whether some promises are successful or not.
The above is the detailed content of How Can I Wait for All Promises to Settle, Even if Some Fail?. For more information, please follow other related articles on the PHP Chinese website!