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
- 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.
true, the deferred returned by
when2will resolve as soon as any of the passed deferreds resolves. In this case,
.donecallbacks will be passed
indexis the index of the deferred that fired. If non-deferreds are in the arguments to
when2, the first one seen will trigger the resolve (not very useful, but consistent).
false, the deferred returned by
when2will 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
failwill be called on the deferred returned by
when2on the first error (this is the behavior of
jQuery.when). The args passed to
value, indicating which deferred was rejected.
.progresscallbacks added to the returned deferred are also called with
valuearguments 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.