How to Sync call in Node.js

北城余情 提交于 2019-12-08 07:29:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!