Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 56 ยท AJAX

Deferreds, Promises and Ajax Events

Work with the jqXHR promise: done, fail, always, then, $.when for parallel requests, jQuery 3 Promises/A+ rules, global ajax events, ajaxPrefilter and fetch.

Every AJAX call returns an object, and so far we mostly ignored it in favor of success and error options. That object, the jqXHR, is a promise: a placeholder for a result that does not exist yet. Attaching callbacks to it gives you cleaner code, lets you combine several requests, and plugs directly into modern async/await syntax.

This lesson covers the promise methods, how $.when() waits for several requests at once, how jQuery 3 aligned its promises with the Promises/A+ standard, the global events that fire for every request, and how to hand the whole thing over to native Promise and fetch().

A promise has three states

Pending The request is still running.
Resolved .done() callbacks run.
Rejected .fail() callbacks run.

.always() runs for both. A settled promise never changes again.

1 / 2

done, fail, always

JavaScript
var request = $.getJSON("/api/users/1");

request.done(function (user, textStatus, jqXHR) { /* success */ });
request.fail(function (jqXHR, textStatus, errorThrown) { /* failure */ });
request.always(function () { /* hide the spinner */ });

The callbacks get the same arguments as the matching $.ajax() options. Three advantages over options:

  1. You can attach callbacks after the call, and as many as you like, from different parts of the code.
  2. Callbacks added to an already finished request still run (right away).
  3. The same object can be passed around, returned from functions and combined with others.

The old jqXHR.success() and .error() methods were removed in jQuery 3, so use .done() and .fail().

A function that returns the promise lets its caller decide what happens next:

JavaScript
function loadUser(id) {
  return $.getJSON("/api/users/" + id);
}
loadUser(1).done(render).fail(showError);

then and chaining

.then(onDone, onFail) is the general tool. It returns a new promise, so you can chain steps, and what you return from a handler becomes the input of the next step. If you return another promise (such as a second request), the chain waits for it.

JavaScript
$.getJSON("/api/users/1")
  .then(function (user) {
    return $.getJSON("/api/orders?user=" + user.id);   // wait for this one
  })
  .then(function (orders) {
    console.log(orders.length + " orders");
  })
  .catch(function () {
    console.log("one of the two requests failed");
  });

.catch(fn) is shorthand for .then(null, fn). This is a sequence: the second request starts only after the first one returns, which is right when it needs the first answer.

$.when(): requests in parallel

When requests do not depend on each other, start them together and wait for all. $.when() takes several promises and resolves when every one has resolved. It rejects as soon as any one fails.

JavaScript
$.when($.getJSON("/api/users/1"), $.getJSON("/api/orders?user=1"))
  .done(function (userResult, ordersResult) {
    var user = userResult[0];      // each argument is [data, textStatus, jqXHR]
    var orders = ordersResult[0];
  });

Because each jqXHR resolves with three values, $.when() hands you an array of them for each request, so the data is at index 0. With a single promise argument you get the plain values. The time saved is real: two parallel requests take as long as the slower one, not the sum.

Sequential versus parallel

The sequential version takes about 800 ms, the parallel one about 500 ms, and $.when() reports a failure after only 200 ms without waiting for the slow request.

jQuery 3 and Promises/A+

Before version 3, jQuery's promises behaved differently from the promises in the rest of the JavaScript world. jQuery 3 made .then() follow the Promises/A+ specification. The practical differences:

  • Always asynchronous. A .then() handler never runs synchronously, even when the promise is already resolved. It runs on a later tick. (.done() and .fail() are still synchronous when the promise has already settled.)
  • Exceptions become rejections. If a .then() handler throws, the promise returned by .then() is rejected and the next .catch() handles it. In old versions the exception escaped and broke the chain.
  • One value per step. A .then() result is passed on as a single value.
  • .catch() exists, as do the native-compatible patterns, so jQuery promises can be mixed with other libraries.
  • .pipe() is deprecated; use .then().
Order of execution and error handling

Global ajax events

Besides per-request callbacks, jQuery fires global events for every request. They are ideal for one central loading indicator or an error logger. Attach them with .on() to document:

JavaScript
$(document).on("ajaxStart", function () { $("#spinner").show(); });
$(document).on("ajaxStop", function () { $("#spinner").hide(); });
$(document).on("ajaxError", function (event, jqXHR, settings, thrownError) {
  console.warn("Request failed:", settings.url, jqXHR.status);
});
Event Fires Extra arguments
ajaxStart When the first request begins while none is active none
ajaxSend Before each request is sent jqXHR, settings
ajaxSuccess After each successful request jqXHR, settings, data
ajaxError After each failed request jqXHR, settings, thrownError
ajaxComplete After each request, either way jqXHR, settings
ajaxStop When the last active request finishes none

Set global: false on a request (for background polling, say) to keep it from triggering these events. The older shorthand methods such as .ajaxStart(fn) still exist, but .on("ajaxStart", fn) is the recommended style.

ajaxSetup and ajaxPrefilter

$.ajaxSetup(options) changes defaults for all later requests, for example $.ajaxSetup({ timeout: 8000 }). The jQuery team discourages it for anything beyond a timeout, because it silently affects code (including plugins) you did not write.

$.ajaxPrefilter(fn) is more precise. The function sees each request's settings before it is sent and may change them, so it is the right place to add a base URL, an auth header or logging.

JavaScript
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  options.headers = $.extend({ "X-App": "tutorial" }, options.headers);
});

Pass a data type as the first argument ($.ajaxPrefilter("json", fn)) to limit the filter to requests of that type.

Events, a prefilter and a spinner

In the "Two at once" case, ajaxStart and ajaxStop each appear once, which is why they are the right hooks for a single spinner.

Moving to native Promises and fetch

A jqXHR is a thenable, so native code can consume it directly. await unwraps it, and Promise.resolve() converts it to a real Promise:

JavaScript
async function showUser(id) {
  try {
    var user = await $.getJSON("/api/users/" + id);   // resolves with the data
    $("#name").text(user.name);
  } catch (jqXHR) {                                    // rejects with the jqXHR object
    $("#name").text("Failed: " + jqXHR.status);
  }
}

Two details: await receives only the first resolved value (the data), and a failure throws the jqXHR object, not an Error. If you convert with Promise.resolve($.ajax(...)), you keep the same behaviors.

Many projects eventually replace the jQuery calls with fetch(). A rough equivalent of the loadUser function above:

JavaScript
async function loadUser(id) {
  const response = await fetch("/api/users/" + id);
  if (!response.ok) { throw new Error("HTTP " + response.status); }
  return response.json();
}

Note one big difference: fetch() does not reject on a 404 or 500, so you must check response.ok yourself, while jQuery rejects automatically. More recipes are in From jQuery to Modern JavaScript.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the userResult and ordersResult arguments passed to $.when(a, b).done(...), where is the response data?

    A jqXHR resolves with three values, so $.when() collects them into an array for each request. The data comes first.
  2. 2. What happens to a .then() handler that throws an error in jQuery 3?

    jQuery 3 follows Promises/A+, where exceptions inside then handlers become rejections.
  3. 3. You have three requests running and want one spinner. Which events do you use?

    ajaxStart fires when the first request begins and ajaxStop when the last one finishes, so they bracket the whole group.
  4. 4. Why does a fetch()-based replacement need an extra response.ok check?

    fetch() only rejects on network failures. jQuery rejects for any non-2xx status, so code ported to fetch must test response.ok.

Summary

  • The jqXHR returned by every AJAX call is a promise: use .done(), .fail(), .always() and .then() / .catch(); the old .success() and .error() are gone.
  • Chain .then() for dependent requests and use $.when() for independent ones; its results arrive as [data, textStatus, jqXHR] arrays.
  • jQuery 3 .then() follows Promises/A+: handlers are asynchronous, and thrown errors become rejections.
  • Global events (ajaxStart, ajaxStop, ajaxError, ...) on document support central spinners and logging; global: false opts a request out.
  • $.ajaxPrefilter() modifies request settings centrally; $.ajaxSetup() changes defaults, so use it sparingly.
  • A jqXHR works with await and Promise.resolve(); with fetch() you must check response.ok yourself.

Next, put these tools together in Real-World AJAX Patterns.