jQuery Deferred’s, $.when() and the fail() callback arguments

$.when() will execute the failed callback (2nd parameter passed to then()) immediately if any one of the parameters fails. It’s by design. To quote the documentation: http://api.jquery.com/jQuery.when/ In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still … Read more

jQuery: execute array of functions sequentially (both deferreds and non-deferreds)

Very astute, jQuery.when is what you’re looking for. It takes either a promise or a normal non-thenable and returns a promise over that value. However, since you have functions and not values here that isn’t really required since this is the behavior of .then anyway. var queue = [syncFunction, syncFunc2, returnsPromiseAsync]; var d = $.Deferred().resolve(); … Read more

jQuery.when understanding

function showData(data1, data2) { alert(data1[0].max_id); alert(data2[0].max_id); } function method1() { return $.ajax(“http://search.twitter.com/search.json”, { data: { q: ‘ashishnjain’ }, dataType: ‘jsonp’ }); } function method2() { return $.ajax(“http://search.twitter.com/search.json”, { data: { q: ‘ashishnjain’ }, dataType: ‘jsonp’ }); } $.when(method1(), method2()).then(showData);​ Here’s a working jsFiddle

How to chain ajax calls using jquery

With a custom object function DeferredAjax(opts) { this.options=opts; this.deferred=$.Deferred(); this.country=opts.country; } DeferredAjax.prototype.invoke=function() { var self=this, data={country:self.country}; console.log(“Making request for [” + self.country + “]”); return $.ajax({ type: “GET”, url: “wait.php”, data: data, dataType: “JSON”, success: function(){ console.log(“Successful request for [” + self.country + “]”); self.deferred.resolve(); } }); }; DeferredAjax.prototype.promise=function() { return this.deferred.promise(); }; var countries … Read more

Throwing an Error in jQuery’s Deferred object

Now updated for jQuery 1.8+ The easiest way to tackle this is to run the response of $.ajax through .then to filter based on success or failure of the data. $.ajax() .then(function (response) { return $.Deferred(function (deferred) { var problem = hasError(response); if (problem) { return deferred.reject(problem) } deferred.resolve(response); }).promise(); }); You could then return … Read more

What are deferred objects?

Deferred Object As of jQuery 1.5, the Deferred object provides a way to register multiple callbacks into self-managed callback queues, invoke callback queues as appropriate, and relay the success or failure state of any synchronous or asynchronous function. Deferred Methods: deferred.done() Add handlers to be called when the Deferred object is resolved. deferred.fail() Add handlers … Read more