How to Use jQuery .done() with Deferred Objects

In jQuery, the .done() method is used to attach callbacks that execute immediately when a Deferred object is resolved, signaling the successful completion of an asynchronous task. This article explains how the .done() method functions, provides clear code examples for creating and resolving a $.Deferred() object, and demonstrates how to handle success callbacks using common implementations like AJAX requests.

Understanding the .done() Method

The .done() method binds one or more functions to be called when a Deferred object transitions to the "resolved" state. If the Deferred is already resolved when the callback is attached, the callback executes immediately with the arguments that were passed to the original resolve() call.

Syntax

deferred.done(function(args) {
    // Code to run when resolved
});

You can pass a single function, an array of functions, or multiple function arguments to a single .done() call.

Using .done() with a Custom Deferred Object

To use .done() with a custom asynchronous operation, create an instance using $.Deferred(), attach your callback using .done(), and trigger it using .resolve().

function performTask() {
    var dfd = $.Deferred();

    setTimeout(function() {
        // Resolve the Deferred with data
        dfd.resolve("Task completed successfully!");
    }, 1000);

    // Return the promise to prevent external state tampering
    return dfd.promise();
}

// Attach the callback
performTask().done(function(message) {
    console.log(message); // Outputs: "Task completed successfully!" after 1 second
});

Using .done() with jQuery AJAX

A primary use case for .done() is handling asynchronous HTTP requests. The $.ajax(), $.get(), and $.post() methods return a jqXHR object, which implements the jQuery Promise interface.

$.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    method: "GET"
}).done(function(data, textStatus, jqXHR) {
    console.log("Data received:", data);
    console.log("Status:", textStatus);
});

The callback function passed to .done() in an AJAX request receives the response data, the text status of the request, and the jqXHR object.

Attaching Multiple Callbacks

You can attach multiple callbacks to a single Deferred object. They will execute in the exact order they were added.

var dfd = $.Deferred();

// Chained callbacks
dfd.done(function() {
    console.log("First callback executed.");
}).done(function() {
    console.log("Second callback executed.");
});

// Pass multiple functions in one call
function notifyUser() {
    console.log("Notification sent.");
}

function updateUI() {
    console.log("UI updated.");
}

dfd.done(notifyUser, updateUI);

// Trigger all callbacks
dfd.resolve();