node.js writing your own async parallel control flow

Here is an asynchronous parallel control flow function. It takes an array of functions and a callback function. Each function in the array has to have one callback function. The functions in the array are not executed in order. The result of each function is saved in the results and passed to the final callback function. When all the functions in the array are completed its executions, the final results are passed to the callback function. If one of the functions passed an err to the callback, the final callback will be called immediately with the error object. The remaining functions will left unprocessed.

var parallel = function (arr, callback) {
    callback = callback || function () {};
    if (!arr.length) {
        return callback();
    }
    var index = 0;
    var results = [];
    arr.forEach(function (fn) {
    	fn(function (err, result) {
    		if (err) {
    			callback(err);
                        callback = function () {};
    		} else {
    			index++;
    			results.push(result);
    			if (index >= arr.length) {
    				callback(null, results);
    			}
    		}
    	});
    });
};


// Simulate async operations by using the setTimeout function with random timeout value. All it does is the print the number passed into the function. 
var asyncTask = function(num) {
    return function (cb) {
        setTimeout(function() {
            console.log(num);
            cb(null, num);
        }, Math.random()*1000);             
    }
};
 
// An array of asyncTask
var tasks = [
    asyncTask(1),
    asyncTask(2),
    asyncTask(3),
    asyncTask(4),
    asyncTask(5)
    ];
 
// run the async tasks in parallel
parallel(tasks, console.log);

// The order of the result varies over time
// 4
// 2
// 1
// 3
// 5
// null [ 4, 2, 1, 3, 5 ]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search