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
- How do you make AJAX requests with jQuery?
- What is the difference between .html() and .text(), and why does it matter for security?
- What is event delegation, and why is it useful?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What is the difference between .attr() and .prop()?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?