如何返回一个嵌套的承诺

how to return a nested promise?

本文关键字:一个 嵌套 承诺 返回 何返回      更新时间:2023-09-26

我有一个像这样的javascript函数:

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

上面的代码不能工作,因为foo()会在returnPromise被赋值之前退出。asyncMethod3和4只能在asyncMethod1和2完成后执行。关于如何构建我的javascript函数有什么建议吗?

您可以直接链接then调用

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

注意:您不必命名函数表达式,我这样做是为了清晰。