3

I want a promise which will itself resolve when two promises promise1 and promise2 are BOTH resolved. How do I do this?

Here is my current horrible code:

            var c = 0;
            var d = $.Deferred();
            promise1.then(() => {
                c++;
                if (c == 2) {
                    d.resolve();
                }
            });
            promise2.then(() => {
                c++;
                if (c == 2) {
                    d.resolve();
                }
            });
            return d.promise();

Is there a helper function I can call instead?

Tim Lovell-Smith
  • 15,310
  • 14
  • 76
  • 93
  • 4
    `$.when` does this for you, including proper error handling. – Bergi Aug 05 '14 at 17:38
  • 1
    @Bergi Although in the browser everything tends to be an ajax promise, I certainly didn't think of searching for the answer that way. – Tim Lovell-Smith Aug 05 '14 at 18:04
  • I know, but there were also some other non-ajax questions on this subject (e.g. [Wait for multiple deferred to complete](http://stackoverflow.com/q/14733156/1048572)) closed as duplicates of that canonical question. I guess the keywords were *wait* and *all* or *multiple*. – Bergi Aug 05 '14 at 18:29

3 Answers3

3

Use .when

Something like

$.when(promise1, promise2).then(function() { /* do something */ });

This will let you group one or more deferreds and do something only when they have all been resolved. Or calls the failCallback if any one of them fails.

When the master deferred resolves, it will be passed the resolved values of all the component deferreds.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
2

You want jQuery's .when().

Check out the docs for a full example. Here's the gist:

$.when( $.ajax("/myURL/"), someOtherDeferred ).done(function( a1, a2 ) {
   // ... Both deferrals are complete!
});

Note that $.ajax creates a "deferred object" (like a promise), so the two are interchangeable.


If you want to perform something even if a promise fails, use .always() instead of .done().

Casey Falk
  • 2,617
  • 1
  • 18
  • 29
2
$.when(promise1, promise2).then(resolution)
Amadan
  • 191,408
  • 23
  • 240
  • 301