Chain dependent requests with then()

Use the result of the first call to make the second, and handle every failure in one place.

jQuery · Chain dependent requests with then()Advanced
function loadProfile(userId) {
  return $.getJSON('/api/users/' + userId)
    .then(function (user) {
      return $.getJSON('/api/orders', { user: user.id || userId });
    })
    .then(function (orders) {
      return { count: (orders.items || []).length };
    });
}

loadProfile(7)
  .done(function (result) { $('#orders').text(result.count + ' orders'); })
  .fail(function () { $('#orders').text('Could not load'); });
thenpromisechainingajax