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

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

DDD
DDDOriginal
2024-12-16 12:36:12334browse

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

Waiting for All Promises to Complete, Despite Rejections

In asynchronous programming, dealing with promises can present challenges when some tasks fail. Let's consider the following scenario:

const arr = [fetch('index.html'), fetch('http://does-not-exist')];

Promise.all(arr)
  .then(res => console.log('success', res))
  .catch(err => console.log('error', err)); // This is executed

The above code makes network requests using fetch. However, since Promise.all will reject upon the first failed request, we encounter an issue: how can we handle the results of all tasks, even those that failed?

Native JavaScript Solution

To address this problem, we can employ the following native JavaScript techniques:

  1. Using reflect to Create a Wrapper Promise:
const reflect = p => p.then(v => ({ v, status: "fulfilled" }), e => ({ e, status: "rejected" }));

This reflect function returns a new promise that resolves to an object containing either the resolved value or the rejection reason, along with a status property indicating the promise's state.

  1. Applying Reflect to All Promises:
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");
});

In this example, we apply reflect to each promise in the array. The resulting array now contains an object with status and error or value properties for each request.

Modern Alternative: Promise.allSettled

For a modern solution, consider using the built-in Promise.allSettled:

Promise.allSettled([promise]).then(([result]) => {
  // Code will execute regardless of the promise's state
  // { status: "fulfilled", value: 33 }
});

This method provides a convenient way to handle all settled promises, regardless of their outcome.

By leveraging these techniques, you can gracefully manage asynchronous operations and access the results of all promises, even those that fail, allowing you to make informed decisions based on the available data.

The above is the detailed content of How Can I Handle All Promises, Including Rejected Ones, in Asynchronous JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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