I have an asynchronous function that works with the result of two other async functions.
Till now what I was doing is that I write function2 in the callback function1 and function2 in the callback of function2
function1(callbackFunction() {
function2(callbackFunction() {
function3()
})
})
Is there any other way to handle this. I work usually with JavaScript code in client side and in nodeJs.
My scenario is that for function2 I don't need output from function1. In another words function1 and function2 are independent; but function3 is dependent on function1 and function2.
I want my function2 to run independent on function1 but function3 to run dependent on both functio1 and function2.
Is there anything like
function1();
function2();
when(funtion1.complete && funtion2.complete) {
function3();
}
There are some good libraries to deal with orchestrating asynchronous functions.
async
andq
(or other Promises/A libraries) help.If
function2
does not depend on the result offunction1
, you can execute them in parallel. Here's how it looks usingasync
(these examples assume that your callback has afunction(err, result)
signature, which is the defacto pattern for Node:If
function2
depends on the result fromfunction1
,waterfall
may be a better pattern:Personally, I like
q
, because you can pass promises around and do all kinds of nifty stuff. Here's how this would look using that:Or if
function1
andfunction2
can be done in arbitrary order:Here is a solution that I baked. You can try a call manager to call the dependant functions
With the current config provided above, when it is run the output is given as -