Learn all about the jQuery function jQuery.Deferred().
jQuery.Deferred() factory creates a new
jQuery.Deferred method can be passed an optional function, which is called just before the method returns and is passed the new
deferred object as both the
this object and as the first argument to the function. The called function can attach callbacks using
deferred.then(), for example.
A Deferred object starts in the pending state. Any callbacks added to the object with
deferred.fail() are queued to be executed later. Calling
deferred.resolveWith() transitions the Deferred into the resolved state and immediately executes any
doneCallbacks that are set. Calling
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.
Enhanced Callbacks with jQuery Deferred
jQuery.ajax() accept callbacks to be invoked some time in the near-future upon success, error, and completion of the ajax request.
jQuery.Deferred() introduces several enhancements to the way callbacks are managed and invoked. In particular,
jQuery.Deferred() provides flexible ways to provide multiple callbacks, and these callbacks can be invoked regardless of whether the original callback dispatch has already occurred. jQuery Deferred is based on the CommonJS Promises/A design.
One model for understanding Deferred is to think of it as a chain-aware function wrapper. The
deferred.fail() methods specify the functions to be called and the
deferred.reject(args) methods "call" the functions with the arguments you supply. Once the Deferred has been resolved or rejected it stays in that state; a second call to
deferred.resolve(), for example, is ignored. If more functions are added by
deferred.then(), for example, after the Deferred is resolved, they are called immediately with the arguments previously provided.
In most cases where a jQuery API call returns a Deferred or Promise-compatible object, such as
jQuery.when(), you will only want to use the
deferred.fail() methods to add callbacks to the Deferred’s queues. The internals of the API call or code that created the Deferred will invoke
deferred.reject() on the deferred at some point, causing the appropriate callbacks to run.