angularjs foreach loop through http requests depen

2019-07-21 17:32发布

问题:

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");
                })
          }
        }

回答1:

You need to continue to chain each subsequent request while looping over the array/hash.

Conceptually it would look like this:

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);
      });
    }
  });
}

And just to get a better understanding, here is a Plunker that shows how to perform this chaining.