1

I have a javascript function looks like this:

function foo() {

    var returnPromise;

    $.when(asyncMethod1(), asyncMethod2()).then(
        function() {
            //… process results from method1 and 2
            returnPromise = $.when(asyncMethod3(), asyncMethod4()).then(
                function() {
                    finalMethod();
                }
            );
        });
    return returnPromise;
}

The code above would not work because foo() will exit before returnPromise gets assigned. asyncMethod3 and 4 can only be executed after asyncMethod1 and 2 are completed. Any suggestion on how to structure my javascript function?

E.A.
  • 321
  • 1
  • 4
  • 13

1 Answers1

3

You can just chain then calls.

function foo() {
    return $.when(asyncMethod1(), asyncMethod2()).then(function(resultOf1, resultOf2) {
        return $.when(asyncMethod3(), asyncMethod4());
    });
}

foo().then(function finalMethod(resultOf3, resultOf4) {});

Note: You do not have to name the function expression, I did it for clarity.

plalx
  • 42,889
  • 6
  • 74
  • 90
  • For completeness, you may want to show the args in the first `.then()` callback that come from the results of `asyncMethod1()` and `asyncMethod2()` since the OP says they want to use those results in the next two async calls. – jfriend00 May 17 '14 at 03:17
  • The ans above does not work. foo() is returned before asyncMethod1 and asyncMethod2 (forget about 3 and 4) are done. In your code, finalMethod() will be the first method to be executed. – E.A. May 17 '14 at 14:58
  • 1
    @E.A. This will work if `asyncMethod1()` and `asyncMethod2()` and `asyncMethod3()` and `asyncMethod4()` return promises. That's what `$.when()` requires in order to do its job. So, if you're seeing the behavior you describe, then those asyncMethods must not be returning promises that are resolved when their corresponding async operation is complete. – jfriend00 May 17 '14 at 16:15
  • Thx jfriend, you nailed it! – E.A. May 20 '14 at 05:07