我想做这样的事情:
given:
a = [a bunch of promises]
b = [another bunch of promises]
c = [more promises]
do:
return Bluebird.all(a, b, c).spread((resolved_a, resolved_b, resolved_c) => {
// do stuff
})
这似乎不起作用。当给定多个单独的承诺或单个承诺时,Promise.all效果很好。
谢谢!
@安迪·加斯科尔(Andy Gaskell),
使用传播版本,我没有得到我想要的行为。
鉴于:
a = an array with three promises that resolve to 'a', 'b', and 'c'
b = like a but resolves 'd', 'e', 'f'
d = like a but resolves 'g', 'h', 'i'
return Bluebird.all(a, b, c,).spread((ra, rb, rc) => {
console.log(ra) // 'a', 'b', 'c'
console.log(rb) // 'd', 'e', 'f'
console.log(rc) // 'g', 'h', 'i'
}
我想将已解决的承诺保留在.then()中。扩展或收缩数组会使它们变平,因此将已解决的承诺合并到一个数组中。
也许这不可能吗?
@tincot
您的方法几乎已经存在,已解决的承诺结构完美,但是似乎并不能同时执行(我认为,尚未完全说服自己)。
最佳答案
就像数组是嵌套的一样,因此您也可以嵌套.all
调用。
这里带有本机的承诺,但是对于蓝鸟来说是一样的:
const a = [Promise.resolve('a'), Promise.resolve('b'), Promise.resolve('c')];
const b = [Promise.resolve('d'), Promise.resolve('e'), Promise.resolve('f')];
const c = [Promise.resolve('g'), Promise.resolve('h'), Promise.resolve('i')];
Promise.all([a, b, c].map(x => Promise.all(x))).then(responses => {
console.log(responses); // [["a","b","c"],["d","e","f"],["g","h","i"]]
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
所有的诺言将立即创建,最后的诺言将在最后一个原始诺言得到解决时解决。以下是上述片段的一种变体,它说明了这一点:
const delayed = (ms, val) => new Promise( resolve => setTimeout(_ => resolve(val), ms) );
var a = [delayed( 500, 'a'), delayed( 700, 'b'), delayed( 300, 'c')];
var b = [delayed( 200, 'd'), delayed(1000, 'e'), delayed( 800, 'f')];
var c = [delayed( 600, 'g'), delayed( 900, 'h'), delayed( 400, 'i')];
Promise.all([a, b, c].map(x => Promise.all(x))).then(responses => {
console.log(responses); // [["a","b","c"],["d","e","f"],["g","h","i"]]
});
setTimeout(_ => console.log('all should be resolved'), 1050);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 在bluebird中,同时执行多个promise数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44087848/