Home > Article > Web Front-end > 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(); });
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!