angularjs foreach loop through http requests dependent on previous request

一个人想着一个人 提交于 2019-12-24 03:09:28

问题


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.



来源:https://stackoverflow.com/questions/27157511/angularjs-foreach-loop-through-http-requests-dependent-on-previous-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!