François Richard
François Richard

Reputation: 7035

promises sequence combination with Q

I wanted to create dynamically a sequence of promise dynamically passing its result to the next promise.

So I did this (took this from the documentation)

this.actions.reduce(Q.when, Q());

where this.actions is an arrray of functions which return promises. [f1,f2,f3]. This is working well we have a nice dynamically created promise sequence.

What I want to do now is a little bit more complicated and can't find how to do it (however I believe it's possible, i'm just missing something here).

I would like to be able to create the same things but with several promises executing at the same time (something with q.all I guess) Here is the explanation: this.actions = [f1,[f2,f3],f4]

f1 is executed and it's result is passed to both f2 and f3. f2 and f3 are executed simultaneously and both results are passed to f4 when both done f4 is executed and can use f2&f3 results

So we have a sequence of promises just like the first example but some elements of this sequence can be group of promises passing all their results to the next elements of the sequence (another promise or group of promises).

I guess it's not really hard to do but I'm a bit confused how to build this.

thanks a lot!

Upvotes: 1

Views: 51

Answers (1)

Bergi
Bergi

Reputation: 664247

You're looking for

f1().then(x => Q.all([f2(x), f3(x)])).then(f4)

or, if writing the chain as a reduction sequence,

[f1, x => Q.all([f2(x), f3(x)]), f4].reduce(Q.when, Q())

To programmatically build the function that runs f2 and f3 concurrently, you can use

function concurrently(fns) {
    return x => Q.all(fns.map(fn => fn(x)));
}

[f1, concurrently([f2, f3]), f4].reduce(Q.when, Q())

Upvotes: 1

Related Questions