Created
September 24, 2012 20:58
-
-
Save digitalicarus/3778331 to your computer and use it in GitHub Desktop.
calls array of async functions and invokes callback when all done - shindig
This file contains 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
/** | |
* 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