1

I want to build an array of objects but for each object I need multiple chained http calls. Eg:

var objects = [];
$http.get(/getDataUrl)
.then(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }
   }
   for(i = 0; i < objects.length; i++)
   {
       http.get(objects[i].value1)
       .then(function(data){
           objects[i].value2 = data.value;
       }
   }
})

Any ideas how to properly execute this mess?

user3816378
  • 93
  • 14

3 Answers3

2

You will always get 'i' value to be the final index because the renderer will print it when the ajax request gives 200, this will take some time. And in that short time, the for loop would have been executed, therefore you will always get the last index for the value of 'i'

To solve this, you will have to use, closure inside loops

Modify your code like as follows,

var objects = [];
$http.get(/getDataUrl)
.success(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }
   }
   for(i = 0; i < objects.length; i++)
   {
       (function(index) {
           var currentURL = objects[i].value1;

           $http.get(currentURL)
           .success(function(data) {

               // both currentURL and i value can be accessed here 
               console.log(currentURL);
               console.log(index); // i value  = index

               objects[index].value2 = data.value;
           });
       })(i);
   }
})

Now you have access of index inside the anonymous function. Hope this helps

Community
  • 1
  • 1
akashrajkn
  • 2,295
  • 2
  • 21
  • 47
0

You can try to use success instead of then, as $http isn't a standard promise :

var objects = [];
$http.get('/getDataUrl')
.success(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }
   }
   for(i = 0; i < objects.length; i++)
   {
       http.get(objects[i].value1)
       .success(function(data2){
           objects[i].value2 = data2.value;
       }
   }
})
Freezystem
  • 4,494
  • 1
  • 32
  • 35
0

Try something like that : Only one loop to rules them all ;)

$http.get(/getDataUrl)
.then(function(data){
   for(i = 0; i < data.length; i++)
   {
       objects[i] = { value1 : data.value }


       $http.get(objects[i].value1)
       .then(function(data){
           objects[i].value2 = data.value;
       }
    }

})
aorfevre
  • 5,034
  • 3
  • 21
  • 51