0

I'm playing with Marvel API as I'm building a character showcase however Marvel limits the amount of results you can retrieve in a single get request to 100.

I've tried to put it inside the for loop but it isn't working. I have tried to implement a method suggested as a solution while or for loop with $http.get

My code:

var loopRequests = function(i){
      $scope.offsetParam = 0;
      $http.get($scope.baseUrl, {
        params: {
          offset: $scope.offsetParam,
          limit: 100,
          ts: $scope.timeStamp,
          apikey: $scope.publicKey,
          hash: $scope.hash
        }}).then(function(response){

        $scope.characters = response.data.data.results;

      });
}

for(var i = 0; i < 2; i++){
  loopRequests(i);
  $scope.offsetParam += 100;
}

Here's what I'm trying to achieve:

  • Request 1: Offset 0, Limit 100
  • Request 2: Offset 100, Limit 100
  • Request 3: Offset 200, Limit 100
  • Request 4: Offset 300, Limit 100 etc...

Any help with this will be appreciated.

//Edit: It needs to wait for the last request to finish

georgeawg
  • 48,608
  • 13
  • 72
  • 95
A.C
  • 23
  • 1
  • 5
  • Do you have to wait for the last request to finish? – zero298 Mar 19 '19 at 21:17
  • @zero298 Edit. Yes, it has to finish loading the first 100 before loading next 100 – A.C Mar 19 '19 at 21:21
  • You should add that in your question. – zero298 Mar 19 '19 at 21:36
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). The `loopRequests` function creates a closure with `$scope.offsetParam`. – georgeawg Mar 19 '19 at 21:59

1 Answers1

0

I think you need to pass in the offset param, otherwise it will be overwritten by your for loop.

You can use $q.all() to wait for a list of promises:

var loopRequests = function(offset){
    return $http.get($scope.baseUrl, {
        params: {
          offset: offset,
          limit: 100,
          ts: $scope.timeStamp,
          apikey: $scope.publicKey,
          hash: $scope.hash
        }});
}

var promises = [];

for(var i = 0; i < 2; i++){
    $scope.offsetParam += 100;
    promises.push(loopRequests($scope.offsetParam));
}

$q.all(promises).then(results => console.log(results))
jsdeveloper
  • 3,945
  • 1
  • 15
  • 14