简体   繁体   中英

How to run a callback when all running in parallel function done their job?

I got stack with the question: "How to run a callback after all async functions done their job"

Here an example:

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

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

I do not want to run a task after another. The idea to run them in parallel, but I need that callback right after all done. Does nodeJs have build-in feature for it?

For now I'm using a combination of an EventEmitter and counter. Every time when a task is finished it runs an event. Because I know how many tasks have ran. I can count it and emit callback. But must be more flexible way. Here what I use now.

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

Is there another way to do it?

You can use the async library, https://github.com/caolan/async

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

Use a counter:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM