Home > Web Front-end > JS Tutorial > How to Handle Individual Errors in Promise.all and Access Unaffected Promise Data?

How to Handle Individual Errors in Promise.all and Access Unaffected Promise Data?

Mary-Kate Olsen
Release: 2024-10-29 18:29:50
Original
987 people have browsed it

How to Handle Individual Errors in Promise.all and Access Unaffected Promise Data?

Catching Errors in Promise.all

Problem:

When using Promise.all to handle an array of promises, catching individual promise errors is challenging as Promise.all returns the first encountered error and disregards the rest. Consequently, data from unaffected promises in the array becomes inaccessible.

Solution:

The inherent behavior of Promise.all is to return an array of resolved values or reject with a single error upon rejection of any member promise.

However, you can modify your code as follows to handle individual errors while still receiving values from successful promises:

existingPromiseChain = existingPromiseChain.then(function() {
  var arrayOfPromises = state.routes.map(function(route) {
    return route.handler.promiseHandler()
      .then(function(data) {
        return data;
      })
      .catch(function(err) {
        return { error: err };
      });
  });
  return Promise.all(arrayOfPromises);
});

existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
  // do stuff with my array of resolved promises (values or error objects), eventually ending with a res.send();
});
Copy after login

Explanation:

By catching errors individually and returning error objects, you allow Promise.all to resolve with an array that contains both resolved values and error objects. Your subsequent then() block can then handle this mixed array accordingly.

The above is the detailed content of How to Handle Individual Errors in Promise.all and Access Unaffected Promise Data?. 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