【问题标题】:How to Sync call in Node.js如何在 Node.js 中同步调用
【发布时间】:2013-10-16 21:51:18
【问题描述】:

我有以下代码sn-p:

var  array = [1, 2, 3];
var data = 0;
for(var i=0; i<array.length; i++){
  asyncFunction(data++);
}
console.log(data);
executeOtherFunction(data);

我期望数据值为 3,但由于asyncFunction,我将其视为 0。当所有asyncFunction 呼叫完成后,我如何呼叫executeOtherFunction

【问题讨论】:

  • 这是您的实际代码,还是试图简化它?实际上,data 的值在 console.log 行处为 3,这正是您所期望的。
  • 已编辑。是的,这不是确切的代码。我给出了一个简化的逻辑,但这是它的确切流程。
  • 好的,但我的意思是,您发布的代码完全符合人们的预期。您应该不简化它,直到它表现出有问题的行为。
  • 我的 asyc 函数在一个循环中被多次调用,我需要利用一些由 async 函数更新的数据。以及最后一次执行异步函数时。我需要利用所有异步调用生成的所有数据调用不同的方法

标签: node.js asynchronous iife


【解决方案1】:

使用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);
});

(假设asyncFunction 有两个参数,一个数字(data)和一个回调)

【讨论】:

  • 我建议使用别名async.forEach,它与async.each 相同,但更明显的是它是forEach 的异步版本
  • @Plato 我什至不知道它的存在!将从现在开始使用它,肯定更有意义:)
【解决方案2】:

如果asyncFunction 实现如下:

function asyncFunction(n) {
    process.nextTick(function() { /* do some operations */ });
}

那么您将无法知道asyncFunction 何时实际执行完毕,因为它已离开调用堆栈。所以它需要在执行完成时通知。

function asyncFunction(n, callback) {
    process.nextTick(function() {
        /* do some operations */
        callback();
    });
}

这是使用简单的回调机制。如果您想使用异常多的模块之一来为您处理此问题,请继续。但是用基本回调实现类似的东西可能并不漂亮,但并不困难。

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】:

    看看这个模块,我想这就是你要找的:

    https://github.com/caolan/async

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2017-04-13
      • 2016-07-30
      • 1970-01-01
      相关资源
      最近更新 更多