jQuery-when2 – a more flexible way to work with jQuery deferreds
I’ve often been frustrated by the limited functionality of jQuery.when. You give it some deferred objects and it fires when all the deferreds are finished. The trouble is, if any of the deferreds is rejected the deferred returned by jQuery.when
fires immediately. So you can’t use it to collect the results of all deferreds including any errors. You also can’t use it to fire when the first of the passed deferreds fires.
So last night I wrote a new version of when, called jQuery-when2 that offers the three behaviors that I commonly want:
- resolve on the first success,
- fail on the first error (the
jQuery.when
behavior), or - resolve when all results (successes or errors) have been collected.
The API differences from jQuery.when:
when2
must be called with a list as its first argument.- An
options
Javascript object may be passed as a second argument. - If
options.resolveOnFirstSuccess
istrue
, the deferred returned bywhen2
will resolve as soon as any of the passed deferreds resolves. In this case,.done
callbacks will be passedindex
andvalue
args, whereindex
is the index of the deferred that fired. If non-deferreds are in the arguments towhen2
, the first one seen will trigger the resolve (not very useful, but consistent). - If
options.failOnFirstError
isfalse
, the deferred returned bywhen2
will never fail. It will collect the results from all the deferreds and pass them all back. The caller gets to figure out which values (if any) are errors. - If no options are given (or
options.failOnFirstError
istrue
),fail
will be called on the deferred returned bywhen2
on the first error (this is the behavior ofjQuery.when
). The args passed tofail
will beindex
andvalue
, indicating which deferred was rejected. - Any
.progress
callbacks added to the returned deferred are also called withindex
andvalue
arguments so you can tell which deferred made progress.
You can grab the source code, see examples, etc., on Github.
BTW, I’m writing a short (about 75pp) O’Reilly book, Learning jQuery Deferreds, with Nicholas Tollervey. If you’re interested in reviewing early Rough Cuts drafts, please let me know! The book will be out late this year.
You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.