仅保留来自解析和忽略被拒绝的Promises的值 [英] Keep the values only from the Promises that resolve and ignore the rejected

查看:66
本文介绍了仅保留来自解析和忽略被拒绝的Promises的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列承诺,每个承诺都是要求废弃网站。他们中的大多数解决但可能是一个或两个拒绝的情况,例如该网站已关闭。我想要的是忽略被拒绝的承诺并保留已经解决的承诺的价值。

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 不适用于那种情况,因为它需要所有承诺才能解决。

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

Promise.some()不是我想要的,因为我事先不知道有多少承诺会解决。

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

Promise.any() Promise.some()相同有计数1.

这个案例如何解决?我正在使用蓝鸟实施

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

推荐答案

当然,幸运的是,蓝鸟已经这样做了:

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
});

这篇关于仅保留来自解析和忽略被拒绝的Promises的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆