Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Deferred

The $.Deferred object

Let's start with the Deferred object — understanding it and knowing how to use it is basically next-level wizardry. Let's see how it works, open up our sandbox:

Run this script in the console:

// initialize the Deferred object
// status is "pending"
var D = $.Deferred();

// attach handlers
D.then(function() { console.log("first") });
D.then(function() { console.log("second") });

// change the status to "fulfilled" — "completed successfully"
// to do this we call resolve()
// for clarity, let's wait a second
// our handlers will be called in order, but they don't wait for each other
setTimeout(() => D.resolve(), 1000)

// this handler is attached too late and will be called immediately
D.then(function() { console.log("third") });

The examples above will work on any page where jQuery is included ;)

If we translate all this into plain English, we get the following scenario:

  • if everything goes well, then run this function and output "first"

  • and also this function — "second"

  • resolve() — we found out everything is fine

  • if everything is fine, run the function and output "third"

Besides "happy ending" scenarios, there are also sad stories when things don't go as we'd like:

So it goes like this:

  • if everything goes well, then run this function — "done"

  • if everything goes wrong, then this function will output "fail"

  • oops, everything went wrong

In reality, the then() method allows you to attach handlers for both the positive scenario and the error case simultaneously:

Does this make the code more readable? I doubt it, but this pattern exists and is used everywhere. Personally, I prefer using the catch() method to handle errors, which is essentially just shorthand for then(null, fn):

I'll also mention the always() method — it adds handlers that will execute regardless of the outcome (under the hood, it calls done(arguments) and fail(arguments)).

To avoid confusion with all these methods, here's a flowchart:

When calling resolve() and reject(), you can pass arbitrary data to the registered callback functions for further processing:

On top of that, there are resolveWith() and rejectWith() methods — they let you change the context of the called callback functions (i.e., inside them "this" will point to the specified context):

One more thing worth noting — if you're going to pass the Deferred object to someone else so they can attach their event handlers, but you don't want to lose control, then return not the object itself, but the result of the promise() method — effectively, this will be the same object in "read-only" mode:

available methods
will be unavailable

then, done, fail, always, pipe, progress, state and promise

resolve, reject, notify, resolveWith, rejectWith, and notifyWith

And besides the "waiting for a miracle" behavior, with Deferred you can build call chains — "live queues":

We've already implemented similar behavior using the animate() method, but we want to find our own way:

Before jQuery 1.8, we used the pipe() method here, but now it's then()

In this example, we call the then() method and pass it a callback function that should return a Promise object. This is necessary to maintain order in the queue — try removing one "return" from the example, and you'll notice the next animation starts without waiting for the previous one to finish:

But the Deferred possibilities don't end here. There's also a pair of methods notify() and progress() — the first sends messages to callback functions registered by the second. Here's a clear example to demonstrate (open the console and see what happens):


Experience the full power of Deferred!

Let's create a service for searching images on Flickr. We'll start with an object that handles loading data from Flickr:

Now let's run the search and process the server response:

As a result, we get a simple little search service:

Last updated