【问题标题】:How to run a callback when all running in parallel function done their job?当所有并行运行的函数完成他们的工作时如何运行回调?
【发布时间】:2013-04-15 05:20:19
【问题描述】:

我的问题是: “如何在所有异步函数完成工作后运行回调”

这里是一个例子:

function doTasks(**callback**) {
   doTask1(function() {
   ...
   });

   doTask2(function() {
   ...
   });
}

我不想一个接一个地运行一个任务。并行运行它们的想法,但我需要在完成后立即进行回调。 nodeJs 有内置功能吗?

现在我正在使用 EventEmitter 和计数器的组合。每次任务完成时,它都会运行一个事件。因为我知道已经运行了多少任务。我可以数数并发出回调。但必须采用更灵活的方式。这是我现在使用的。

var EventEmitter = require("events").EventEmitter;

var MakeItHappen = module.exports = function (runAfterTimes, callback) {
    this._aTimes                = runAfterTimes || 1;
    this._cTimes                = 0;
    this._eventEmmiter          = new EventEmitter();
    this._eventEmmiter.addListener("try", callback);
}

MakeItHappen.prototype.try = function () {
    this._cTimes += 1;
    if (this._aTimes === this._cTimes) {
        this._cTimes = 0;
        this._eventEmmiter.emit("try", arguments);
    }
}

还有其他方法吗?

【问题讨论】:

    标签: node.js asynchronous


    【解决方案1】:

    您可以使用异步库,https://github.com/caolan/async

    async.parallel([
        function(){ ... },
        function(){ ... }
    ], callback);
    

    【讨论】:

      【解决方案2】:

      使用计数器:

      var a = function (cb){
          //Asynchronous stuff
          cb ();
      };
      
      var b = function (cb){
          //Asynchronous stuff
          cb ();
      };
      
      var remaining = 2;
      
      var finish = function (){
          if (!--remaining){
              //a and b finished...
          }
      };
      
      a (finish);
      b (finish);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-10
        • 1970-01-01
        • 2013-08-18
        • 1970-01-01
        • 2022-06-15
        • 2018-11-05
        • 1970-01-01
        相关资源
        最近更新 更多