我有一个 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/