SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Chaining with .then()

Chaining with .then()

.then() on a jQuery Deferred returns a new Promise whose value is the return value of the callback — enabling sequential async chains.

Example
$.getJSON("/api/users/1")
  .then(function(user) {
    return $.getJSON("/api/orders?userId=" + user.id);
  })
  .then(function(orders) {
    return $.getJSON("/api/items?orderId=" + orders[0].id);
  })
  .then(function(items) {
    renderItems(items);
  })
  .fail(function(err) {
    console.error("Chain failed:", err);
  });
Pro Tip

A single .fail() at the end catches errors from any step in the chain.