Sean Sean - 1 month ago 7
Javascript Question

Promises: How to execute async methods in parallel then execute method

I'm using Q.js for promises. In the following code, each method makes an ajax call and then returns a promise. Everything works as expected with each method executing and completing before the next begins:

functionOne().then(junctionTwo)
.then(functionThree)
.then(doSomethingElse);


What I would really like however is for functionOne, functionTwo and functionThree to all be executed simultaneously and "doSomethingElse" should be executed only when the first 3 methods are complete.

How do you accomplish this with promises/Q.js?

Answer

You can use the now-standardized Promise.all() to tell you when an array of promises are all done:

Promise.all([functionOne(), functionTwo(), functionThree()]).then(function(results) {
    // all are done here
    doSomethingElse();
}).catch(function(err) {
    // error in at least one promise here
});

Or, if you're still using the Q library syntax, then you can use Q.all() which does the same thing.

Q.all([functionOne(), functionTwo(), functionThree()]).then(function(results) {
    // all are done here
    doSomethingElse();
}).catch(function(err) {
    // error in at least one promise here
});

You should know that in node.js or the browser, there is no "simultaneously" because JS is single threaded (outside of webWorkers which are not being used here). But, if your operations are asynchronous (which I assume since they return promises), then they can all three be in flight at the same time though only one is executing at any given moment.