jQuery interview question · Most asked

What are jQuery Deferreds, and how do you wait for several requests?

Summary

A Deferred is jQuery's promise implementation: it can be resolved or rejected, and handlers attach with .done(), .fail(), .always() and .then(). $.when(a, b) waits for several deferreds (such as AJAX calls) and resolves when all succeed, or rejects as soon as one fails.

Longer Answer

$.when($.getJSON("/api/user"), $.getJSON("/api/orders"))
  .done(([user], [orders]) => render(user, orders))
  .fail(() => showError());

Each AJAX argument resolves with an array [data, textStatus, jqXHR], hence the destructuring. You can create your own with $.Deferred() to wrap callback APIs. In modern code, Promise.all and async/await work with jqXHR objects too, because since jQuery 3 they are Promises/A+ compatible.

Key Points

  • Deferred = jQuery promises.
  • $.when for parallel waits.
  • AJAX resolves with [data, status, xhr].
  • Interoperates with native promises in 3.x.

More most-asked jQuery questions

← All jQuery questions