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.whenbehavior), or - resolve when all results (successes or errors) have been collected.
The API differences from jQuery.when:
when2must be called with a list as its first argument.- An
optionsJavascript object may be passed as a second argument. - If
options.resolveOnFirstSuccessistrue, the deferred returned bywhen2will resolve as soon as any of the passed deferreds resolves. In this case,.donecallbacks will be passedindexandvalueargs, whereindexis 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.failOnFirstErrorisfalse, the deferred returned bywhen2will 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.failOnFirstErroristrue),failwill be called on the deferred returned bywhen2on the first error (this is the behavior ofjQuery.when). The args passed tofailwill beindexandvalue, indicating which deferred was rejected. - Any
.progresscallbacks added to the returned deferred are also called withindexandvaluearguments 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.
