0

With jQuery I know that I can use $.when() to wait for all of multipe Deferreds to be resolved. (Or for the first one to be rejected.)

But is there a simple way to fire of multiple Deferreds and then just wait for the first one to be resolved?

For instance I want to try to use two similar AJAX web services either or which might be down or slow and then process whichever one replies first. And then I might use a third Deferred for a timeout.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
  • See also [Find first available data source with jQuery Deferred](http://stackoverflow.com/questions/11089335/find-first-available-data-source-with-jquery-deferred) – hippietrail Aug 15 '12 at 21:07
  • I filed another feature request against jQuery for this and related enhancements to `$.when()`: **[OPTIONS PARAMETER FOR $.WHEN() TO PROVIDE ALTERNATIVE SEMANTICS](http://bugs.jquery.com/ticket/12325)**. It was also closed but [jaubourg](https://github.com/jaubourg) added good analysis and suggestions that will help anyone interested in this question. – hippietrail Aug 17 '12 at 12:25

2 Answers2

2

Based on Kevin B's code, here's an approach that uses a master Deferred object:

var masterDeferred = new $.Deferred(),
    reqOne = $.post("foo.php"),
    reqTwo = $.post("bar.php");

masterDeferred.done(function() {
    // do stuff
});

reqOne.done(function() {
    masterDeferred.resolve();
});
reqTwo.done(function() {
    masterDeferred.resolve();
});

I think I'm right in saying that the simplest form of resolving the masterDeferred would be :

reqOne.done(masterDeferred.resolve);
reqTwo.done(masterDeferred.resolve);

But separate done functions will allow you to branch internally and call .resolve(), .reject(), .resolveWith(...) or .rejectWith(...) as appropriate, together with masterDeferred callbacks of the general form :

masterDeferred.then( doneCallbacks, failCallbacks );
Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44
  • Isn't there a risk that masterDeferred() will be called twice? Is there a defined behaviour for that? – hippietrail Aug 15 '12 at 21:47
  • No risk at all. A Deferred object (or its Promise) can only be resolved or rejected ONCE. Further attempts to resolve or reject will do precisely nothing, and will not generate an error providing the Deferred (or its Promise) has not been destroyed (and is within scope). – Beetroot-Beetroot Aug 15 '12 at 22:11
1

A quick and easy way would be to abort the other request when one of the two finishes, though you could also check the state of the deferred, the syntax of which will depend on your jQuery version which is why I go with abort for now.

function doStuff(data) {
    alert( "Hello World!" );
}
var reqOne = $.post("foo.php"),
reqTwo = $.post("bar.php");

reqOne.done(function(data){
    reqTwo.abort();
    finished = true;
    doStuff(data);
});
reqTwo.done(function(data){
    reqOne.abort();
    finished = true;
    doStuff(data);
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180