gpt4 book ai didi

javascript - 如何返回嵌套的 promise ?

转载 作者:行者123 更新时间:2023-11-30 12:43:01 25 4
gpt4 key购买 nike

我有一个 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) {});

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

关于javascript - 如何返回嵌套的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23706579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com