Skip to content

Instantly share code, notes, and snippets.

@patrickseda
Created September 6, 2012 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickseda/3657055 to your computer and use it in GitHub Desktop.
Save patrickseda/3657055 to your computer and use it in GitHub Desktop.
A CommonJS module providing the ability to pause program flow until a set of asynchronous operations have completed.
/**
* Provides the ability to have a set of asynchronous operations wait after their
* respective execution until all of the operations in the group have completed.
*
* Sample usage:
* // Define some operations that will run asynchronously.
* var worker1 = function(announceComplete) {
* // Do some work here ...
* announceComplete();
* };
* var worker2 = function(announceComplete) {
* // Do some work here ...
* announceComplete();
* };
*
* // Callback for when all workers have completed.
* var allCompleteCB = function() {
* alert('All operations completed, Latch is released.');
* };
*
* // Use the Latch to run the workers asynchronously.
* var latch = require('Latch');
* latch.start([worker1, worker2], allCompleteCB);
*
* @author Patrick Seda
*/
var Latch = (function() {
// Start all operations asynchronously.
var start = function(workers, allCompleteCB) {
var counter = workers.length;
// Decrement counter and fire the CB when all workers are finished.
var announceComplete = function() {
if (--counter === 0) {
allCompleteCB && allCompleteCB();
}
};
// Start each worker, handing them the announceComplete method.
for (var i = 0, len = workers.length; i < len; i++) {
workers[i](announceComplete);
}
};
// Public API
return {
start : start
};
})();
module.exports = Latch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment