ddibiase
ddibiase

Reputation: 1502

Parallel promise return in order

I'm looking for an efficient way in Bluebird (or native Promise if necessary) to run a parallel array of promises and return them in order as they are completed. Almost like a queue lock, I guess?

So if I have an array of 5 functions, function 1 could take 150ms, function 2 could take 50ms, function 3 could take 50ms etc. All 5 functions are called in parallel but the callbacks returning values would only respond in the order I specify. Ideally something like this:

Promise.parallelLock([
    fn1(),
    fn2(),
    fn3(),
    fn4(),
    fn5()
])
.on('ready', (index, result) => {
    console.log(index, result);
})
.then(() => {
    console.log('Processed all');
})
.catch(() => {
    console.warn('Oops error!')
});

I think I can accomplish this with Bluebird coroutines? Just having trouble deciding structure that makes most sense/is most aligned with my above example.

Upvotes: 2

Views: 214

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

That's just Promise.all which just waits for all promises, a promise is like a value - if you have a promise the action was already performed:

Promise.all([
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1()
])
.then(results => {
    // this is an array of values, can process them in-order here
    console.log('Processed all');
})
.catch(() => {
    console.warn('Oops error!')
});

If you need to know when one is done, you can .tap (a then which doesn't change the return value)them through.mapbefore passing them to.all`:

Promise.all([
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1()
].map((x, i) => x.tap(v => console.log("Processed", v, i))
.then(results => {
    // this is an array of values, can process them in-order here
    console.log('Processed all');
})
.catch(() => {
    console.warn('Oops error!')
});

Upvotes: 3

Related Questions