Monday, March 10, 2014

Deferred in JQuery

Web applications are kept alive by data. These data usually retrieved from data sources. AJAX (Asynchronous JavaScript and XML) is a technique used to communicate with web servers to send and receive data asynchronously. Often you'll send a ajax request, wait for data to come inside callbacks and execute rest of the flow. Ajax uses XMLHttpRequest object to communicate with server side.


XMLHttpRequest object
Is used to exchange data between client and server. Using this you can update web pages without reloading or send data to server in background.

Below is how you can create a simple ajax request using jQuery. You can pass object to as a parameter which contains settings for the ajax request. jQuery.ajax() will return a jqXHR object. jqXHR is a superset of native XMLHttpRequest. As of jQuery 1.5, jqXHR object implements the Promise interface.

There are variety of options you can use to customize the ajax requests.



Also you can use jQuery.ajaxSetup() to set defaults for future Ajax requests but using this not recommended.

When you have multiple ajax requests to send you'll need some mechanism to chain them to have correct sequencing you desire. Also you'll need to make the requests asynchronously to make browser not getting freezed (you can make Ajax requests synchronous but it is not advisable). in jQuery you can use Deferred for this.


jQuery Deferred is widely used when handling ajax requests. Understanding how it works is important to correctly use them in different scenarios.

In the jQuery documentation it says, 
  • A Constructor function 
  • That returns a chainable utility object
  • with methods to register multiple callbacks into callback queues,
  • invoke callback queues,
  • and relay the success or failure state of any sync or async function 
A Deferred object starts in the pending state. Calling deferrred.resolve() or deferred.resolveWith() transitions the Deferred into resolved state. 

We'll look at some functions we'll come across when using deferred and promises


jQuery.when() see documentation


Provides a way to execute callback functions based on one or more objects. (Usually Deferred objects which represents async. events)

If a single Deferred is passed to .when(), it's Promise object is returned by the method.
If a single argument is passed to .when(), and if it is not a deferred or a promise, it will be treated as resolved and any done callbacks will be executed immediately.

When multiple Deferreds are passed to when the method returns the Promise from a new "master" Deferred object.

If deferred was resolved without no value, the corresponding done callback will be undefined.
Another example of jQuery.when() behavior


deferred.done()

Add handlers to be called when the Deferred object is resolved. 

When Deferred is resolved, done callbacks are called in the order they were added. done() returns the deferred object, therefore other methods of the deferred object including additional .done callbacks can be chained.



then() vs done()
then() vs done() 2

deferred.then()

Add handler  to be called when the Deferred object is resolved, rejected or still in progress. Returns a new promise object.

Since .then() returns a promise, other methods of the Promise object can be chained to this, including .then() methods.

Let's see an example. Notice the output and compare it with done example above,



Lets look at another simple example,

You can see that if async = false, the example will simply look like calling few functions directly.

deferred.always()
Add handlers to be called when the Deferred object is either resolved or rejected. Returns Deferred object.

deferred.promise()

Return Deferred's promise object


Difference between Deferred and Promise objects


Deferred can resolve itself but promise can only attach events to itself. Promise cannot resolve itself.

var a = $.when(func1())
            .done(func2); //returns a promise
 var b = $.Deferred(); //returns a Deferred  

Promise Object 
Subset of methods of the Deferred object to prevent users from changing the state of Deferred object.

SO



Deferred examples


Resources

http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics 

http://colonelpanic.net/2011/11/jquery-deferred-objects/ 
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

http://learn.jquery.com/code-organization/deferreds/jquery-deferreds/

http://www.html5rocks.com/en/tutorials/async/deferred/

http://stackoverflow.com/questions/4869609/how-can-jquery-deferred-be-used

http://stackoverflow.com/search?q=jQuery.ajaxSetup()

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook