The Deferred object, introduced in jQuery 1.5, is a chainable utility object created by calling the jQuery.Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
Similar to jQuery object, Deferred object is also chainable. $.Deferred() / jQuery.Deferred() is a constructor that creates a new deferred object. A Deferred object starts in the pending state. Any callbacks added to the object with deferred.then(), deferred.always(), deferred.done(), or deferred.fail() are queued to be executed later. Calling deferred.resolve() or deferred.resolveWith() transitions the Deferred into the resolved state and immediately executes any doneCallbacks that are set. Calling deferred.reject() or deferred.rejectWith() transitions the Deferred into the rejected state and immediately executes any failCallbacks that are set. Once the object has entered the resolved or rejected state, it stays in that state. Callbacks can still be added to the resolved or rejected Deferred — they will execute immediately.
- deferred.always(), deferred.done(), deferred.fail() return the deferred object.
- deferred.then(), deferred.when(), .promise() return a promise.
- $.ajax() and $.get() return promise objects
- instead of using .resolveWith() and .rejectWith(), you can call resolve with the context you want it to inherit
- pass the deferred.promise() around instead of the deferred itself as the deferred object itself cannot be resolved or rejected through it.