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?
 
    