javascript-在AngularJS中依次运行$http请求
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-在AngularJS中依次运行$http请求,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1888字,纯文字阅读大概需要3分钟。
内容图文
![javascript-在AngularJS中依次运行$http请求](/upload/InfoBanner/zyjiaocheng/680/560c88376e344707b02fcd7312bbf512.jpg)
我的$scope上有一系列项目.对于每个项目,我需要运行三个$http请求.无论是否失败,这些请求都必须以特定的顺序运行.我不确定如何使用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 :)由于.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请求全部内容,希望文章能够帮你解决javascript-在AngularJS中依次运行$http请求所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。