Fupslot
Fupslot

Reputation: 125

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?

Upvotes: 1

Views: 832

Answers (2)

Gabriel Llamas
Gabriel Llamas

Reputation: 18437

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

Upvotes: 2

Deathspike
Deathspike

Reputation: 8780

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

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

Upvotes: 4

Related Questions