Skip to content

Instantly share code, notes, and snippets.

@digitalicarus
Created September 24, 2012 20:58
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 digitalicarus/3778331 to your computer and use it in GitHub Desktop.
Save digitalicarus/3778331 to your computer and use it in GitHub Desktop.
calls array of async functions and invokes callback when all done - shindig
/**
* Calls an array of asynchronous functions and calls the continuation
* function when all are done.
* @param {Array} functions Array of asynchronous functions, each taking
* one argument that is the continuation function that handles the result
* That is, each function is something like the following:
* function(continuation) {
* // compute result asynchronously
* continuation(result);
* }.
* @param {Function} continuation Function to call when all results are in. It
* is pass an array of all results of all functions.
* @param {Object} opt_this Optional object used as "this" when calling each
* function.
*/
shindig.callAsyncAndJoin = function(functions, continuation, opt_this) {
var pending = functions.length;
var results = [];
for (var i = 0; i < functions.length; i++) {
// we need a wrapper here because i changes and we need one index
// variable per closure
var wrapper = function(index) {
var fn = functions[index];
if (typeof fn === 'string') {
fn = opt_this[fn];
}
fn.call(opt_this, function(result) {
results[index] = result;
if (--pending === 0) {
continuation(results);
}
});
};
wrapper(i);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment