Sunday, March 23, 2014

JQuery: Deferred Object

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.
In computer science, future, promise, and delay refer to constructs used for synchronizing in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete. A deferred is an object representing work that is not yet done and a promise is an object representing a value that is not yet known. In other words, promises / deferreds allow us to represent ‘simple’ tasks and can be easily combined to represent complex tasks and their flows, allowing for fine-grained control over sequencing. This means we can write asynchronous JavaScript parallel to how we write synchronous code. Additionally, promises make it relatively simple to abstract small pieces of functionality shared across multiple asynchronous tasks.
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 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.
Key Points:
  • deferred.always(), deferred.done(), 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.