Created
September 6, 2012 14:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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