*Required Fields
Ready to do it yourself?

Introducing Beacon, the most robust survey and reporting toolset available for market research and CRM activities.

Working with jQuery’s $.Deferred

3 comments 06.02.2011

jQuery, the write less, do more javascript framework has a long standing history of making web developers look good, while at the same time enabling us to write less code.  Recently, in version 1.5 of jQuery we were introduced to the $.Deferred method and it allows us to do some pretty cool things.

So, what can we use $.Deferred for?  Well, for starters, it’s built right into the jQuery AJAX methods.  Code suddenly becomes cleaner and more expressive because we can now chain together our callbacks rather than passing them into the ajax function:

$.ajax(‘/some/url’,{data:’foo=bar’}).done(function(res){
    //success - winning!
}).fail(function(res){

    //error - Y U NO WORK RIGHT???
});

The above code is possible because the $.ajax method now returns a promise object, which exposes several methods for working with the result of our asynchronous functions. If a deferred is “resolved”, then the done()methods are called. If the deferred is “rejected”, the fail() methods are called. The promise object also gives us a then() method which takes up to two callback arguments, the first being a success (done) function and a second optional callback for failure states.

Where else can we use $.Deferred? What about animations? jQuery’s animation methods take as an optional argument a callback method, to be called after the animation is complete. We can use this as a way to resolve our deferred, and fire any callbacks that are waiting for the resolution.

I was recently writing a progress bar widget that I wanted to make animated. I ended up writing a function like:

var ProgressBar = {
    advance : function(percent){
        return $.Deferred(function(dfr){
            $(‘.progressbar’).animate({width:percent + ‘%’}, dfr.resolve);
        }).promise();
    }
};

The code above will perform the animation, and as soon as it’s done, my deferred will be resolved, and my callbacks will fire.

ProgresBar.advance(86).then(function(){
    //do something neat
});

Another interesting example I’ve seen floating around the web for using deferred is to create a more readable setTimeout.

$.wait = function(delay){
    return $.Deferred(function(dfr){
        setTimeout(dfr.resolve, delay);
    }).promise();
};

You could then write timeouts like:

$.wait(1000).then(function(){
    alert(“I’ve waiting long enough”);
});

These are just a few examples of how you can implement jQuery’s deferred method to write more expressive, flexible code. Have other ways you’re putting jQuery’s deferred to work in your own code? I'd love to hear about them in the comments.

Comments

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
Salvatore's picture

Hello, thanks for your article.
$.wait = function(delay){
return $.Deferred(function(dfr){
setTimeout(dfr.resolve, delay);
}).promise();
};

Do we really need chaining with '.promise()' ?
Returning simple defered works

Visitor's picture

Hi Salvatore, sorry for the delay, we've been busy here and I missed this comment. So, yes, your correct, returning the $.Deferred will work, however, if you give the documentation a read, http://api.jquery.com/deferred.promise/, the reason we return the promise is "to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state"

So basically, it's safer. Feel free to post up any more comments or questions here!

nhommua's picture

Thanks for sharing information