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
Deferred() A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
jQuery ajax() Method The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.
AJAX calls are one method to load personalized content separately from the rest of the HTML document, which allows for the full HTML document to be cached, improving back end load time.
What About jQuery and AJAX? jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
Try resolving your initial Deferred as the very last thing:
var d = $.Deferred(),
chained = d;
// optionally chain callbacks with chained = chained.pipe
if (condition) {
chained = chained.pipe(function () {
return $.ajax({...}); // Must return a new Promise
});
}
chained.done(function () {
// all chains should be processed now
});
d.resolve(); // finally, resolve the initial Deferred
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With