Understanding the jQuery $.when() Method

This article explains the purpose, functionality, and practical implementation of the jQuery $.when() method. Readers will learn how $.when() manages asynchronous operations, synchronizes multiple AJAX requests using Deferred and Promise objects, and coordinates callback execution once multiple background tasks are complete.

What Is jQuery $.when()?

The $.when() method in jQuery provides a way to execute callback functions based on the status of one or more objects, primarily Deferred or Promise objects such as those returned by $.ajax(). It functions as a coordinator for asynchronous tasks, effectively acting as jQuery's counterpart to native JavaScript's Promise.all().

When multiple asynchronous tasks must complete before a specific action takes place—such as loading data from two separate API endpoints before rendering a chart—$.when() waits for all supplied tasks to resolve before executing subsequent logic.

Primary Purpose and Core Functionality

The primary purposes of $.when() include:

  1. Synchronizing Multiple Asynchronous Requests: Running multiple AJAX calls simultaneously and waiting for all of them to succeed before continuing.
  2. Aggregating Promises: Combining several promises into a single master promise that reflects the collective outcome.
  3. Handling Mixed Values: Gracefully accepting both asynchronous Promise objects and standard synchronous values or plain JavaScript objects.

Syntax and Basic Example

The method accepts one or more arguments, which can be Deferred objects, Promises, or regular JavaScript values:

$.when( deferreds... ).done( callback ).fail( callback );

Handling Multiple AJAX Calls

In typical usage, $.when() takes multiple $.ajax() requests as arguments:

$.when(
    $.ajax({ url: "/api/users" }),
    $.ajax({ url: "/api/settings" })
).done(function(usersResponse, settingsResponse) {
    // Both requests succeeded
    // usersResponse[0] contains data, usersResponse[1] status, usersResponse[2] jqXHR
    console.log("Users:", usersResponse[0]);
    console.log("Settings:", settingsResponse[0]);
}).fail(function(jqXHR, textStatus, errorThrown) {
    // Fails immediately if either of the requests fail
    console.error("An error occurred:", textStatus);
});

How $.when() Resolves and Rejects

  • All Resolved: The combined promise resolves successfully only when every Deferred object passed to $.when() has resolved. The .done() callback receives the resolved arguments for each Deferred in the order they were supplied.
  • Any Rejected: If any single Deferred object is rejected, the master promise is rejected immediately, triggering the .fail() handler with the arguments passed by the failing request.
  • Non-Deferred Arguments: If a passed argument is not a Promise or Deferred object (for example, a plain number, string, or object), $.when() treats it as an immediately resolved Deferred and passes the value directly to the .done() callback.
  • No Arguments: If called with no arguments ($.when()), it returns an already-resolved Promise.

Summary

The jQuery $.when() method simplifies asynchronous control flow by grouping multiple asynchronous processes into a single manageable unit. It eliminates the need for deeply nested callback structures and guarantees that code dependent on multiple asynchronous data sources only runs once all dependencies are satisfied.