jQuery Deferreds

I’m absolutely loving the new Deferred objects in jQuery 1.5 and am using them heavily in a new project at work.

I just spent a bit of time trying to figure out why they weren’t working the way I was expecting them to, actually having to step into the jQuery code to realize my mistake.

The $.when method can take in one or more Deferred objects, but it can’t take them in as an array. Once I realized this, I immediately realized this could be solved with JavaScript’s apply function like this:

$.when.apply($, myDeferreds).done(function () {
    // All deferreds were resolved...
});

The first argument to apply is the object that gets to be “this” inside the when method. The second argument is the array containing the deferreds.

If myDeferreds contains three deferred objects, the above is the equivalent of this:

$.when(deferred1, deferred2, deferred3).done(function () {
    // All deferreds were resolved...
});

I thought that it would be neat if $.when would check to see if it was passed an array, but the jQuery team disagrees. Here’s hoping I won’t make this mistake again…

One thought on “jQuery Deferreds”

  1. OK. That’s cool and very much along the lines of something I’ve been trying to do. My issue is that I have a variable number of deferred functions being called (actually the same function being called with differing parameters a varying number of times) with parameters. Any ideas about that one? My example:

    $.when(myfunc(‘a’), myfunc(b’), myfunc(‘c’), …).done(funcDoneWhenAllDone);

    Whaddya think?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>