smeckydev smeckydev -4 years ago 116
Javascript Question

In bluebird, execute multiple promise arrays concurrently

I would like to do something like this:

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


This doesn't seems to work. Promise.all works fine when given multiple individual promises, or a single array of promises.

Thank you!

@Andy Gaskell,

Using the spread version, I'm not getting quite the behavior I want.
Given:

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'
}


I want to keep the resolved promises separated in the .then(). Spreading or contracting the arrays flattened them and therefore combined the resolved promises into a single array.

Perhaps this is not possible?

@tincot

Your approach is almost there, the resolved promises are structured perfectly, but do not seem (I think, haven't totally convinced myself yet) to be executing concurrently.

Answer Source

Just like your arrays are nested, so you can also nest the .all calls.

Here with native promises, but it's the same with bluebird:

var a = [Promise.resolve('a'), Promise.resolve('b'), Promise.resolve('c')]; 
var b = [Promise.resolve('d'), Promise.resolve('e'), Promise.resolve('f')]; 
var 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; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download