Deal with it or don't

The simplest explanation of jQuery Deferred

I spent a while trying to get to the bottom of the question, “What is the jQuery Deferred all about?”

I couldn’t find the simple answer (They all seem to include ajax examples), so I decided that the internet needed a very short post about the basics.

Deferred is all about callbacks

Let’s say you are the developer of some asynchronous method. You need to provide a way to callback to the consuming code so that it can be aware of success and failure. One way to do this is to make use of a $.Deferred().

As the author of the method, you would create a new $.Deferred(), and use that* as the return value of the function.
When the real meat of your code has completed, you call the deferred’s .resolve method, and if the meat of your code fails, you call the deferred’s .reject method.

When you call .resolve or .reject, all of the appropriate callbacks that the consumer set up get called.

As the basics, that’s it. Make a Deferred. Call resolve or reject, then the done or fail callbacks get called.

Here’s an example.

function playMonopoly(){
    // long-running code.
    throw new Error("A player gave up.");

function thisMightTakeAWhile(){
    var deferred = $.Deferred();
    return deferred; // *

    console.log("Finished? Wow!");
    console.log("Someone always gives up.");

(You can see it in action on this jsfiddle)

That’s a bad way to use it because nothing there is asynchronous, but that’s the simplicity that I felt the internet was missing.

* Really, you should return deferred.promise()

So what is the difference between a Deferred and a Promise?

The promise is just like returning the Deferred, but with the promise, the consuming code doesn’t have access to the .resolve .reject, and other methods that CHANGE the state. Using the promise, the consuming code only has access to the .done, .fail, etc.


3 responses to “The simplest explanation of jQuery Deferred

  1. Pingback: jQuery Deferred-ified window.setTimeout | Wilsonhut

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: