Javascript angularjs foreach通过依赖于先前请求的http请求进行循环
我想循环一个数组以执行角度为单位的$http.jsonp请求,但是每个请求都会略有不同,具体取决于前一个$http.jsonp请求的时间戳。我试图循环5个请求,每个请求都依赖于以前的请求信息 如何执行foreach循环,等待每个$http请求完成,以便为循环中的下一个$http请求正确更新“lastTime”变量 这是我的密码:Javascript angularjs foreach通过依赖于先前请求的http请求进行循环,javascript,angularjs,foreach,scope,Javascript,Angularjs,Foreach,Scope,我想循环一个数组以执行角度为单位的$http.jsonp请求,但是每个请求都会略有不同,具体取决于前一个$http.jsonp请求的时间戳。我试图循环5个请求,每个请求都依赖于以前的请求信息 如何执行foreach循环,等待每个$http请求完成,以便为循环中的下一个$http请求正确更新“lastTime”变量 这是我的密码: var lastTime = null; function hitUrl(url){ var defer = $q.defer();
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;
})
});
谢谢你的帮助
解决方案
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");
})
}
}
函数hitUrl(端点){
返回$http.jsonp(端点);
};
var承诺;
对于(var i=0;i您需要在数组/散列上循环时继续链接每个后续请求
从概念上看,它是这样的:
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);
});
}
});
}
只是为了更好的理解