Skip to content

Instantly share code, notes, and snippets.

@webholics
Created February 18, 2011 08:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webholics/833428 to your computer and use it in GitHub Desktop.
Save webholics/833428 to your computer and use it in GitHub Desktop.
The barrier can be used to control concurrent flows in NodeJS. It counts how often the function returned is called and executes the callback if it has been called "count" times.
/*
* A barrier that counts how often a function is called.
*/
module.exports = function(count, callback) {
var c = count;
// if count is 0 execute callback
if(c == 0)
callback();
// callback will be executed after this function was called count times
return function() {
c--;
if(c == 0)
callback();
return c;
};
};
var barrier = require("barrier"),
items = [1, 2, 3],
next = barrier(items.length, function() {
console.log("finished");
});
items.forEach(function(i) {
// do something async with i here
setTimeout(next, 1000);
});
@berb
Copy link

berb commented Feb 18, 2011

@webholics
Copy link
Author

Yeah everyone has his barrier ;)
But I like the fact to work only with a little function and I also found it very useful that the callback executes immediately if count is zero.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment