Is it possible to catch all rejected promises in Promise.all?

Given the following

Promise.all(promises).then(resolved => {
    ...
}).catch(rejected => {
    ...
});

rejectedwill only contain the first promise to be rejected. Is there a way to catch all promises that are rejected?

+4
source share
2 answers

Of course, this will require you to wait until all the promises input are set. While someone expects that they can refuse, you cannot be sure that you have all the deviations!

Thus, you can use Promise.all, but after converting the input promises, to catch the deviations and identify them, possibly wrapping them in an object Error, as in

caughtPromises = promises.map(promise => promise.catch(Error));

Promise.all, , :

Promise.all(caughtPromises)
  .then(results => results.filter(result => result instanceof Error))

et voilà.

+11

, promises ( ), - - Promise.settle(). : ES6 Promise.all() - .settle()?

, promises , ( ) , , promises, Promise.all(). promises, Promise.all(), ( ), . , , , promises :

:

Promise.settle(arrayOfPromises).then(function(results) {
    results.forEach(function(pi, index) {
        if (pi.isFulfilled()) {
            console.log("p[" + index + "] is fulfilled with value = ", pi.value());
        } else {
            console.log("p[" + index + "] is rejected with reason = ", pi.reason());
        }
    });
});

. Promise.settle(), .

+1

Source: https://habr.com/ru/post/1662177/


All Articles