我的以下代码有问题:
initPromise = $q.all(arrayOfPromises)
.then(function () {
return $scope.methodWhichReturnsPromise()
.then(function (data) {
console.log("report data");
return data;
});
});
if ($scope.showCompare) {
initPromise
.then(function () {
return $q.all(anotherArrayOfPromises);
})
.then(function () {
return aMethodWhichReturnsAPromise().then(function () {
console.log("compare report data");
});
});
}
initPromise
.then(function () {
console.log("generate view data");
})
.finally(function () {
console.log("finally");
});
根据路由参数加载 Controller 时,我正在加载一堆异步数据。如果存在 showCompare
标志,我想在两者之间加载一些内容。但 console.log
消息的顺序如下:
report data
generate view data
finally
compare report data
我期望比较报告数据
会按照代码中编写的顺序完全显示。
我做错了什么?
最佳答案
您将在 initPromise
上添加两个不同的处理程序,而不是链接所有 .then()
调用。为此,您需要使用
if ($scope.showCompare) {
initPromise = initPromise.then(…);
}
关于javascript - AngularJS $q promise 成功回调以错误的顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18704582/