I want to loop through an array to perform $http.jsonp requests in angular, however each request will be slightly different depending on the timestamp of the previous $http.jsonp request. I'm trying to loop through 5 requests and each request is dependent on the previous request info.
How can I perform a foreach loop that waits for each $http request to finish so that the "lastTime" variable is updated properly for the next $http request in the loop?
Here's my code:
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;
})
});
Thanks for any help!
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");
})
}
}