With jQuery I know that I can use $.when()
to wait for all of multipe Deferred
s to be resolved. (Or for the first one to be rejected.)
But is there a simple way to fire of multiple Deferred
s 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.
Based on Kevin B's code, here's an approach that uses a master Deferred object:
I think I'm right in saying that the simplest form of resolving the masterDeferred would be :
But separate done functions will allow you to branch internally and call
.resolve()
,.reject()
,.resolveWith(...)
or.rejectWith(...)
as appropriate, together withmasterDeferred
callbacks of the general form :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.