Home > Web Front-end > JS Tutorial > How Can I Gracefully Handle Network Failures When Using Promises in JavaScript?

How Can I Gracefully Handle Network Failures When Using Promises in JavaScript?

Patricia Arquette
Release: 2024-12-15 17:21:16
Original
637 people have browsed it

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

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

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

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

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!

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