Web App Development

Introduction to jQuery deferred objects

Deferred objects in jQuery are a concise and readable way to handle multiple asynchronous calls. For example they allow you to avoid nested ajax calls like this:
$.get("http://jsonip.com", function (response1) {
// Get another resource, but just use jsonip.com again as an example.
$.get("http://jsonip.com", function (response2) {
console.log("We know have both response and can continue:");
console.log("Response1: ", response1);
console.log("Response2: ", response2);
Which will show this in the console:
We know have both response and can continue:
Response1: Object {ip: "xx.abc.e.fgh", about: "/about"}
Response2: Object {ip: "xx.abc.d.fgh", about: "/about"}
The code can be rewritten using deferred objects. Another advantage of this is that both ajax calls are made at the same time, avoiding waiting times:
var request1 = $.get("http://jsonip.com");
var request2 = $.get("http://jsonip.com");
$.when(request1, request2).then(function (response1, response2) {
console.log("We know have both response and can continue:");
console.log("Response1: ", response1[0]);
console.log("Response2: ", response2[0]);

How does it work?

The return value of  $.get is a promise object that is assigned to the variables request1 and request2. When the response is available the promise object will be marked as resolved.

$.when also returns a promise object, grouping the two requests. It will mark itself as resolved when both requests that were passed as arguments have been marked as resolved.

Promise objects provide a subset of the functionality of deferred objects. A deferred object can be marked as resolved explicitly while a promise object only provides methods for observers.

(Strictly speaking $.get or $.ajax don't return a promise object but a jqXHR object which is a superset of a promise object.)

Other handler functions

The promise object functions are then, done, always, fail and pip. fail and always allow you to deal with errors that occurred when the request was made. pipe let's you modify the return value of the request before passing it to other handlers.

Alternative callback and control flow libraries

There are some libraries that focus exclusively on facilitating asynchronous control flow. DailyJS has a list.

Learn more

We didn't actually use full-fledged deferred objects in this post - just promise objects. Learn how to use deferred objects for your own components.


Follow me on Twitter