jQuery Deferred is an Ajax Coder’s Dream

As an Innovationeer, I seek out the interesting technological developments that can make my code more elegant. One of those developments has been jQuery’s Deferred object, implemented in jQuery 1.5 and after.

The Problem:
Imagine you’re the referee in a dumptruck race. The first one to reach the finishline and dump the trash is the winner. All the trucks line up at the startline with their payloads and you give the signal. They’re off! There’s no guarantee that Truck #1 will beat Truck #3, in fact the entire point is to see who gets there first. If you bet that you’ll get Truck #3’s trash on top of Truck #1’s at the end, you’ve got an uncertain gamble on your hands.

A series of Ajax calls are like our dumptrucks lining up for a race. There’s no guarantee when any one of them will finish, and you can’t know for certain that the payload of one will arrive before the payload of another. However, in a web application some data is bound to be useless before other data arrives. Until you can get a list of dumptruck drivers, there’s no sense in asking which driver was late to the race.

This is the concept of asynchronous requests (“a” as in “not”, “syn-chron” as in “same time”), and it gains a great boost with the jQuery Deferred object. The Deferred object is a way of telling your code to wait until another set of code has completed, without hanging up the flow of the entire operation (as it would in a synchronous request). In our race analogy, a Deferred object would be the referee making sure the prize doesn’t show up until the race has been won. A Deferred object includes a promise object which is like the race announcer, letting everyone know whether the race has been completed or is still going.

The Code:
Obtaining a promise from an Ajax call is easy, since that’s exactly what a call to $.ajax returns. Since there have been plenty of tutorials on the Deferred object (here’s one ), I’ll share what I’ve been working with specifically.

Here I create an array of two Ajax requests and wait for them to complete by using the $.when .then operator. The functions doSomething and doSomethingDifferent will not execute until both requests have come back with json and json1. Race conditions prevented.

Code on!