I’m looking to queue an arbitrary number of possibly optional function calls in JavaScript/jQuery. For example, I may need to ensure the user is authenticated and a cookie is set before running a second (or third, fourth, etc.) function or AJAX call.
I looked into doing this with the recently added jQuery.Deferred, but found that it doesn’t matter what order the calls are fired in (true async style). Also, I read that once a Deferred instance has been resolved, it’s not possible to un-resolve it.
Here’s where I’m at with this at the moment. Initially, I was thinking of setting the Deferred instance to resolved, then un-resolving it if an optional function came up in the stack.
var d = $.Deferred(),
chained = d,
d.resolve(),
div = extra.find( "div:first" );
if ( extra.attr( "requires-auth" ) != undefined && !config.user_is_authenticated )
chained = chained.pipe( authenticate );
if ( div.length )
chained = chained.pipe( prepareExtra( div ) );
// When the two optional methods are resolved, show the content
chained.done( function() {
extra.fadeIn( 500 )
} );
My question is, what is the best way to queue (0 to N) AJAX calls in pure JavaScript/jQuery? (without using plug-ins).
Tak!
Edit 2: SOLVED!
Here’s some working examples of this, one w/o AJAX and one with:
https://gist.github.com/1021429
https://gist.github.com/1021435
Try resolving your initial Deferred as the very last thing: