1

I have this javascript code:

$.getJSON(url, function(data) {     //Make a call to an api with the a url. 

    // Take the Response field of the json response. 
    // This field contains objects
    var d = data['Response'];             

    for(var i = 0; i < d.length; i++) {     // For each object
        var obj1 = d[i];                    
        var id = obj1['id'];            // Take the id of the object

        var url2 = endpoint+'id='+id                     

        // Make a new api call based on the id of the object
        $.getJSON(url2, function(obj2) {
            console.log(i)
        });
    }
});

For some reason, this prints only the last value of i. Although, when I print the values of i outside the inner block and inside the for block it prints all the values of i.

I also tried to use let instead of var for i but it prints values of i randomly and not sequentialy. It also prints some values twice.

Why is this happening? How can I make the inner block print all the values the i takes during the for loop?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Lora M.
  • 13
  • 4
  • Did you checked this similar question in SO: https://stackoverflow.com/questions/15347750/getjson-and-for-loop-issue – BJohn Apr 22 '19 at 14:49
  • @BJohn Yes and I tried the solution with the ```let``` as I mention in the post but that prints values of ```i``` randomly and not sequentialy. – Lora M. Apr 22 '19 at 14:51
  • That's probably because `getJSON` is async. You might want to refactor to accumulate the data in a top-level object (keyed by index) rather than outputting it immediately. – isherwood Apr 22 '19 at 15:18
  • Read more: https://www.freecodecamp.org/forum/t/how-to-make-loop-of-getjson-calls-wait-for-each-other/134745/3 – isherwood Apr 22 '19 at 15:18

1 Answers1

0

I think is classical problem when callback is called ,as mentioned in the similar question did you try to put the anonymous function inside your loop ? instead of using let ?

$.getJSON(url, function(data) {     //Make a call to an api with the a url. 
        var d = data['Response'];             //Take the Response field of the json response. This field contains objects

        for(var i = 0; i < d.length; i++) {     //For each object
          (function(i) { // protects i in an immediately called function 
          var obj1 = d[i];                    
            var id = obj1['id'];            //Take the id of the object

            var url2 = endpoint+'id='+id
            $.getJSON(url2, function(obj2) {                     //Make a new api call based on the id of the object
                console.log(i)
              });
           })(i);
        }

});

Samir Guiderk
  • 187
  • 2
  • 4
  • 17