0

I need a situation to be handle where I need a loop to execute multiple times for http get call. Here is my code

   for(i = 1; i <= 5; i++){
    console.log(i);
    var req = {
         method: 'GET',
         timeout: 30000,
         url: url
         params: {page_id: i}
      };
      $http(req).success(function(data, status, headers, config) {
          console.log(data);
      }).error(function(data, status, headers, config) {
          console.log('error');
      });      
   }

I need this to handle but not getting the values in order.

2 Answers 2

1

Use a function call in your loop, sample below:

function httpRequestFn(req) {
    $http(req).success(function(data, status, headers, config) {
        console.log(data);
    }).error(function(data, status, headers, config) {
        console.log('error');
    });
}

for(i = 1; i <= 5; i++){
    console.log(i);
    var req = {
        method: 'GET',
        timeout: 30000,
        url: url
        params: {page_id: i}
    };
    httpRequestFn(req);
}
Sign up to request clarification or add additional context in comments.

Comments

0

if you want to send multiple request one shot then i would suggest to use the $q.all

var httpArr = [];
for (i = 1; i <= 5; i++) {
    console.log(i);
    var req = {
        method: 'GET',
        timeout: 30000,
        url: url
        params: {
            page_id: i
        }
    };
    httpArr.push($http(req))
}
$q.all(httpArr).then(function(response) {
    console.log(response[0].data) // 1st request response 
    console.log(response[1].data) // 2nd request response 
    console.log(response[2].data) // 3rd request response 
}).catch(function(response) {
    //error resonse
})

Make sure to inject $q to controller

Comments

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.