我的 $scope
上有一组项目。对于其中的每一项,我都需要运行三个 $http 请求。这些请求必须以特定的顺序运行,无论是否有 not 失败。我不确定如何使用 promise 范式优雅地做到这一点。我有很多重复的代码,看起来真的很困惑。我一定是做错了。目前,我有以下内容:
$scope.items = getItems();
$scope.currentIndex = 0;
$scope.executeItem = function() {
$http.get($scope.items[$scope.currentIndex].urlA).then(
function (resA) {
$scope.items[$scope.currentIndex].urlAWorks = true;
$http.get($scope.items[$scope.currentIndex].urlB).then(
function (resB) {
$scope.items[$scope.currentIndex].urlBWorks = true;
$http.get($scope.items[$scope.currentIndex].urlC).then(
function (resC) {
$scope.items[$scope.currentIndex].urlCWorks = true;
$scope.currentIndex = $scope.currentIndex + 1;
$scope.executeItem();
},
function (errC) {
$scope.items[$scope.currentIndex].urlCWorks = false;
$scope.currentIndex = $scope.currentIndex + 1;
$scope.executeItem();
}
)
},
function (errB) {
$scope.items[$scope.currentIndex].urlBWorks = false;
}
);
},
function (errA) {
$scope.items[$scope.currentIndex].urlAWorks = false;
$http.get($scope.items[$scope.currentIndex].urlB).then(
function (resB) {
$scope.items[$scope.currentIndex].urlBWorks = true;
$http.get($scope.items[$scope.currentIndex].urlC).then(
function (resC) {
$scope.items[$scope.currentIndex].urlCWorks = true;
$scope.currentIndex = $scope.currentIndex + 1;
$scope.executeItem();
},
function (errC) {
$scope.items[$scope.currentIndex].urlCWorks = false;
$scope.currentIndex = $scope.currentIndex + 1;
$scope.executeItem();
}
)
},
function (errB) {
$scope.items[$scope.currentIndex].urlBWorks = false;
}
);
}
);
};
我真的正确地链接了 promise 吗?这看起来很不对。
谢谢
最佳答案
你没有充分利用 promises :) 因为 .then
返回一个 promise,你可以这样做:
$http.get(urlA)
.then(function(dataA){
DoStuffWithA(dataA);
return $http.get(urlB);
})
.then(function(dataB){
DoStuffWithB(dataB);
return $http.get(urlC);
})
.then(function(dataC){
DoStuffWithC(dataC);
return true;
})
关于javascript - 在 AngularJS 中顺序运行 $http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26426081/