Created
March 22, 2010 00:34
-
-
Save dsc/339683 to your computer and use it in GitHub Desktop.
Async chained callback pattern.
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
(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