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.
.then() on a jQuery Deferred returns a new Promise whose value is the return value of the callback — enabling sequential async chains.
$.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);
});
A single .fail() at the end catches errors from any step in the chain.