Skip to content

Instantly share code, notes, and snippets.

@dsc
Created March 22, 2010 00:34
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 dsc/339683 to your computer and use it in GitHub Desktop.
Save dsc/339683 to your computer and use it in GitHub Desktop.
Async chained callback pattern.
(function(){
/**
* Function.asyncChain( fn, [...] ) -> Function
*
* Takes any number of callback functions and returns a scheduler function
* which manages the chain. Each supplied callback to should take one
* argument, the scheduler, to execute with no arguments when it completes.
*
* Example:
*
* // Waits 100ms before doing stuff
* function doA(fn){
* setTimeout(function(){
* console.log("A doing stuff!");
* fn();
* }, 100);
* }
*
* // Makes an ajax request using jQuery and does stuff in the response
* function doB(fn){
* // Note this will not continue the chain on error, as the handler does not fire
* $.getJSON('foo.json', { bar:1 }, function(data){
* console.log("B see reply:", data);
* fn();
* });
* }
*
* var scheduler = Function.asyncChain(doA, doB);
*
* // Kick off chain
* scheduler();
*
*
* Protip: use closures to collect other arguments or context.
*
* Advanced: Note that the scheduler will pass along the execution context
* (this) it is invoked with allowing you to override the return context if
* you wish.
*
*/
function asyncChain(fn){
var callbacks = Array.prototype.slice.call(arguments, 0);
scheduler.add = function(){
var args = Array.prototype.slice.call(arguments, 0);
while (args.length) callbacks.push(args.shift());
};
return scheduler;
function scheduler(){
if ( !callbacks.length )
return;
else
return callbacks.shift().call( this, arguments.callee );
}
}
Function.asyncChain = asyncChain;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment