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
Written by Adam Blackburn
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#