Promises - catching all rejections in a Promise.al

2019-02-22 08:45发布

问题:

This question already has an answer here:

  • Bluebird Promise.all - multiple promises completed aggregating success and rejections 1 answer

I have this dummy code

var Promise = require('bluebird')
function rej1(){
    return new Promise.reject(new Error('rej1'));
}

function rej2() {
    return new Promise.reject(new Error('rej2'));
}
function rej3() {
    return new Promise.reject(new Error('rej3'));
}

Promise.all([rej1(),rej2(),rej3()] ).then(function(){
    console.log('haha')
},function(e){
    console.error(e);
})

In the rejectionHandler i see only the first rejection. Is it possible to view all three rejections?

回答1:

Yes, it is possible to view all three rejections. Promise.all rejects as soon as one promise rejects. Instead - use Promise.settle:

Promise.settle([rej1(), rej2(), rej3()).then(function(results){
    var rejections = results.filter(function(el){ return el.isRejected(); });
    // access rejections here
    rejections[0].reason(); // contains the first rejection reason
});