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

4
  • Do you have to wait for the last request to finish? Commented Mar 19, 2019 at 21:17
  • @zero298 Edit. Yes, it has to finish loading the first 100 before loading next 100 Commented Mar 19, 2019 at 21:21
  • You should add that in your question. Commented Mar 19, 2019 at 21:36
  • Possible duplicate of JavaScript closure inside loops – simple practical example. The loopRequests function creates a closure with $scope.offsetParam. Commented Mar 19, 2019 at 21:59

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

4 Comments

the OP hasn't expressed that the requests need to be sequential - the example given is for parallel requests
true but its not hurting anyone :)
The loopRequest function has a parameter named i which is never used inside the function. The answer make two GET requests both of which return results to the same scope variable.
restructured answer to accommodate waiting for all promises to return

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.