我想循环遍历一个数组以角度执行 $http.jsonp 请求,但是每个请求都会略有不同,具体取决于前一个 $http.jsonp 请求的时间戳。我试图循环 5 个请求,每个请求都依赖于前一个请求信息。
如何执行 foreach 循环来等待每个 $http 请求完成,以便为循环中的下一个 $http 请求正确更新“lastTime”变量?
这是我的代码:
var lastTime = null;
function hitUrl(url){
var defer = $q.defer();
$http.jsonp(url).then(function(res){
console.log(endPoint);
console.log(res);
defer.resolve(res.lasttimestamp);
})
return defer.promise;
};
angular.forEach(hashArray,function(){
if (lastTime = null){
var endPoint = "https://api.com/?callback=JSON_CALLBACK";
}else{
var endPoint = "https://api.com/?aftertimestamp="+lastTime+"&callback=JSON_CALLBACK";
}
hitUrl(endPoint).then(function(res){
console.log(res);
lastTime=res;
})
});
谢谢你的帮助!
Solution
function hitUrl(endPoint){
return $http.jsonp(endPoint);
};
var promise;
for(var i=0;i<5;i++){
if(!promise){
promise = hitUrl("https://api.com/&callback=JSON_CALLBACK");
}else{
promise=promise.then(function(res){
return hitUrl("https://api.com/?aftertimestamp="+lastTime+"&callback=JSON_CALLBACK");
})
}
}
你需要继续链接每个后续请求循环数组/哈希时。
从概念上讲,它看起来像这样:
function callServiceForEachItem() {
var promise;
angular.forEach(items, function(item) {
if (!promise) {
//First time through so just call the service
promise = fakeService.doSomething(item);
} else {
//Chain each subsequent request
promise = promise.then(function() {
return fakeService.doSomething(item);
});
}
});
}
只是为了更好地理解,这是一个 Plunker,展示了如何执行此链接 http://plnkr.co/edit/EIB2qyYDAcSpADVGy4XL?p=preview.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)