Keep the values only from the Promises that resolv

2019-04-20 00:56发布

问题:

I have an array of promises, each promise is a request to scrap a website. Most of them resolve but may are cases that one or two reject e.g. the website is down. What I want is to ignore the rejected promises and keep the values only of the promises that have been resolved.

Promise.all is not for that case since it requires all the promises to resolve.

Promise.some() is not what I want since I don't know beforehand how many promises will resolve.

Promise.any() is the same as Promise.some() with count 1.

How can this case being solved? I am using the Bluebird implementation.

回答1:

Sure thing, lucky for you bluebird already does this:

Promise.settle(arrayOfPromises).then(function(results){
    for(var i = 0; i < results.length; i++){
        if(results[i].isFulfilled()){
           // results[i].value() to get the value
        }
    }
});

You can also use the newer reflect call:

Promise.all(arrayOfPromises.map(function(el){ 
    return el.reflect(); 
})).filter(function(p){ 
    return p.isFulfilled();
}).then(function(results){
    // only fulfilled promises here
});


回答2:

this is same as @Benjamin solution but with more elegant array manipulation:

this code will ignore the rejected promise result, so you may run 10 promises and have the results as array of 3 elements:

Promise.settle(arrayOfPromises).then(function(results){
    return results.filter(function (result) {
               return result.isFulfilled();
            }).map(function (result) {
               return result.value();
            });   
}).then(function(results){
     console.log("here you go:", results);
});

here will ignore the rejected promise but will place null as result so if you run 10 promises you will have the results as array of 10 elements the rejected value will be null:

Promise.settle(arrayOfPromises).then(function(results){
    return results.map(function (result) {
               return result.isFulfilled()? result.value() : null;
            }); 
}).then(function(results){
     console.log("here you go:", results);
});