问题
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?
回答1:
Use async.each:
var async = require('async');
var data = 0;
var array = [ 1, 2, 3 ];
async.each(array, function(item, done) {
asyncFunction(data++, done);
}, function(err) {
if (err) ... // handle error
console.log(data);
executeOtherFunction(data);
});
(assuming that asyncFunction
takes two arguments, a number (data
) and a callback)
回答2:
If asyncFunction
is implemented like the following:
function asyncFunction(n) {
process.nextTick(function() { /* do some operations */ });
}
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.
function asyncFunction(n, callback) {
process.nextTick(function() {
/* do some operations */
callback();
});
}
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.
var array = [1, 2, 3];
var data = 0;
var cntr = 0;
function countnExecute() {
if (++cntr === array.length)
executeOtherFunction(data);
}
for(var i = 0; i < array.length; i++){
asyncFunction(data++, countnExecute);
}
回答3:
Take a look at this module, I think this is what you're looking for:
https://github.com/caolan/async
来源:https://stackoverflow.com/questions/19273700/how-to-sync-call-in-node-js