Home >Web Front-end >JS Tutorial >How Can I Gracefully Handle Network Failures When Using Promises in JavaScript?
Handling Network Failures with Promise Waiting
In JavaScript, Promise.all() is a powerful tool for managing multiple asynchronous operations. However, it may not be suitable when you want all promises to complete, even if some reject.
To handle this scenario, you can implement a custom "Promise Reflect" function that converts promises into objects with fulfilled or rejected status:
const reflect = p => p.then(v => ({ v, status: "fulfilled" }), e => ({ e, status: "rejected" }));
Using this reflect function, you can map the original array of promises to an array of reflected promies:
var arr = [ fetch('index.html'), fetch('http://does-not-exist') ] var reflectedPromises = arr.map(reflect);
Finally, you can use Promise.all() to wait for all reflected promises to complete:
Promise.all(reflectedPromises).then(results => { var success = results.filter(x => x.status === "fulfilled"); });
This approach allows you to handle network failures gracefully and proceed only after all requests have completed. You can access the resolved values and errors from the success and results arrays, respectively.
Alternatively, you can now use the native Promise.allSettled() method:
Promise.allSettled([promise]).then(([result]) => { console.log(result); // Handles both fulfilled and rejected promises });
The above is the detailed content of How Can I Gracefully Handle Network Failures When Using Promises in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!