Handling errors in Promise.all Handling errors in Promise.all javascript javascript

Handling errors in Promise.all


Promise.all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.

Some libraries have something called Promise.when, which I understand would instead wait for all promises in the array to either resolve or reject, but I'm not familiar with it, and it's not in ES6.

Your code

I agree with others here that your fix should work. It should resolve with an array that may contain a mix of successful values and errors objects. It's unusual to pass error objects in the success-path but assuming your code is expecting them, I see no problem with it.

The only reason I can think of why it would "not resolve" is that it's failing in code you're not showing us and the reason you're not seeing any error message about this is because this promise chain is not terminated with a final catch (as far as what you're showing us anyway).

I've taken the liberty of factoring out the "existing chain" from your example and terminating the chain with a catch. This may not be right for you, but for people reading this, it's important to always either return or terminate chains, or potential errors, even coding errors, will get hidden (which is what I suspect happened here):

Promise.all(state.routes.map(function(route) {  return route.handler.promiseHandler().catch(function(err) {    return err;  });})).then(function(arrayOfValuesOrErrors) {  // handling of my array containing values and/or errors. }).catch(function(err) {  console.log(err.message); // some coding error in handling happened});


NEW ANSWER

const results = await Promise.all(promises.map(p => p.catch(e => e)));const validResults = results.filter(result => !(result instanceof Error));

FUTURE Promise API


ES2020 introduces new method for the Promise type: Promise.allSettled().

Promise.allSettled gives you a signal when all the input promises are settled, which means they’re either fulfilled or rejected. This is useful in cases where you don’t care about the state of the promise, you just want to know when the work is done, regardless of whether it was successful.

(async function() {  const promises = [    fetch('//api.stackexchange.com/2.2'), // succeeds    fetch('/this-will-fail') // fails  ];  const result = await Promise.allSettled(promises);  console.log(result.map(promise => promise.status));  // ['fulfilled', 'rejected']})();