How to Sync call in Node.js

2019-05-30 09:40发布

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?

3条回答
可以哭但决不认输i
2楼-- · 2019-05-30 10:41

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楼-- · 2019-05-30 10:43

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)

查看更多
冷血范
4楼-- · 2019-05-30 10:43

Take a look at this module, I think this is what you're looking for:

https://github.com/caolan/async

查看更多
登录 后发表回答