node.js writing your own async series control flow

Async I/O operations in Node.js are not executed in the order the code was written. For example, the following code will not print the numbers from 1 to 5 in order, every time you run it, it will give you numbers 1 to 5 but with different order.

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

// Execute each function in the tasks
tasks.forEach(function (fn) {
	fn(function(){});
});

// The result will be 1 to 5, but not in the order they was executed.
// 5
// 1
// 3
// 4
// 2

Async series 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 will be executed in order. It recursively calls the next function in the array until all the functions in the array are executed. The result of each function is saved in the results and passed to the final callback function. An improvement to this async series function will be to allow the functions in the array to take any number of arguments instead of only one callback function.

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

// 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 series
series(tasks, console.log);

// 1
// 2
// 3
// 4
// 5
// null [ 1, 2, 3, 4, 5 ]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search