Bluebird Promise.all - 多个承诺完成了聚合成功和拒绝

j03*_*03m 29 javascript node.js promise bluebird

今天有人用蓝鸟提出了一个有趣的案例,处理多项承诺的最佳方法是什么,我们对于停止特定的履行或拒绝不感兴趣,而是对检查最终结果感兴趣.一个例子:

var p1 = new Promise(function(f,r){
    setTimeout(function(){
        console.log("p1");
        f("yay");
    }, 100);

});

var p2 = new Promise(function(f,r){
    setTimeout(function(){
        console.log("p2");
        r(new Error("boo"));
    }, 200);

})

var p3 = new Promise(function(f,r){
    setTimeout(function(){
        console.log("p3");
        r(new Error("yay"));
    }, 300);

});

var p4 = new Promise(function(f,r){
    setTimeout(function(){
        console.log("p4");
        f("yay");
    }, 400);

});


//Promise.all([p1,p2, p3, p4]).then(function(p){
//    console.log("Results:",p);
//}).error(function(e){
//    console.log("Error:",e);
//});

Promise.map([p1,p2, p3, p4],function(p){
    console.log("results:",p);
}, {concurrency:10}).error(function(e){
    console.log("Error:",e);
});
Run Code Online (Sandbox Code Playgroud)

在这里,如果我们运行地图或所有被拒绝的承诺将导致处理程序不报告结果.

例如,上面实现的运行Promise.map的结果是:

debugger listening on port 65222
p1
results: yay
p2
Error: [Error: boo]
p3
p4

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

这里每个promise的代码都会执行,但只报告1个结果和1个错误.该错误导致进程停止.

如果我们取消注释.所有我们得到类似的行为.这次,仅报告错误.任何成功都不会成为当时(可以理解).

debugger listening on port 65313
p1
p2
Error: [Error: boo]
p3
p4

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

鉴于这种行为,最好的方法是实施一个方案,在这个方案中,所有承诺都会运行,并且在任何和所有拒绝情况下都会报告履行承诺的结果?

就像是:

Promise.aggregate([p1,p2,p3,p4]).then(function(fulfilled, rejected){
    console.log(fulfilled); //all success
    console.log(rejected); //any and all rejections/exceptions
});
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 36

你用的是.reflect:

Promise.all([p1,p2,p3,p4].map(x => x.reflect()).then(results => {
  results.forEach(result => {
     if(result.isFulfilled()){
         // access result.value()
     } else {
         // access result.reason()
     }
  });
});
Run Code Online (Sandbox Code Playgroud)

这用于与处理settle,传统上就是这样做的一个阵列功能-它是由通用.reflect,因为它从一个承诺检查的概念分离聚合,让你做什么.settle没有,但像其他操作.any.some为好.

  • @BenjaminGruenbaum` .reflect`在最新版本中不适用于我.具体来说,当我按原样运行docs示例时,我得到一个`Uncaught TypeError:promise.reflect不是函数`错误.[其他人](http://bluebirdjs.com/docs/api/reflect.html#comment-2443261819)也询问了`.reflect`.嗯. (4认同)
  • @ silverlight513对不起,我们弃用了 - 虽然它仍然可以使用.前进的方向是使用`.reflect`.感谢您引起我的注意,我会更新答案. (2认同)