Last Updated: February 25, 2016
·
987
· regality314

Node.js Parallel Flow Control

In node.js you sometimes want to make several asynchronous requests simultaneously. You usually start out by writing something like:

var fs = require('fs')
  , fileList = ['file1.txt', 'file2.txt', 'file3.txt']

var numFinished = 0;
function done(err, data) {
  numFinished += 1;
  if (numFinished < fileList.length) return;
  console.log('got all files');
}

for (var i = 0; i < fileList.length; ++i) {
  fs.readFile(fileList[i], done);
}

But it can get tiring and annoying to rewrite that boilerplate all the time. So I wrote a library called waitress, she will take care of things for you:

var fs = require('fs')
  , waitress= require('waitress')
  , fileList = ['file1.txt', 'file2.txt', 'file3.txt']

var done = waitress(fileList.length, function(err, results) {
  console.log('got all files');
});

for (var i = 0; i < fileList.length; ++i) {
  fs.readFile(fileList[i], done);
}

You just give waitress the number of times to wait for the callback to be called, and a callback, and magic! Simple and easy flow control.

You can install waitress with npm install waitress or check it out on github: https://www.github.com/ifit/waitress