Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep the values only from the Promises that resolve and ignore the rejected

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.

like image 646
Avraam Mavridis Avatar asked May 18 '15 17:05

Avraam Mavridis


1 Answers

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
});
like image 147
Benjamin Gruenbaum Avatar answered Sep 23 '22 07:09

Benjamin Gruenbaum