I have following code snippet:
var array = [1, 2, 3];
var data = 0;
for(var i=0; i<array.length; i++){
asyncFunction(data++);
}
console.log(data);
executeOtherFunction(data);
I am expecting value of data as 3 but I see it as 0 due to asyncFunction
. How do I call executeOtherFunction
when all the asyncFunction
calls are done?
If
asyncFunction
is implemented like the following:Then you'll have no way of knowing when
asyncFunction
is actually done executing because it's left the callstack. So it'll need to notify when execution is complete.This is using the simple callback mechanism. If you want to use one of freakishly many modules to have this handled for you, go ahead. But implementing something like with basic callbacks might not be pretty, but isn't difficult.
Use
async.each
:(assuming that
asyncFunction
takes two arguments, a number (data
) and a callback)Take a look at this module, I think this is what you're looking for:
https://github.com/caolan/async