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?

4
  • Did you checked this similar question in SO: stackoverflow.com/questions/15347750/getjson-and-for-loop-issue Commented Apr 22, 2019 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. Commented Apr 22, 2019 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. Commented Apr 22, 2019 at 15:18
  • Read more: freecodecamp.org/forum/t/… Commented Apr 22, 2019 at 15:18

1 Answer 1

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);
        }

});

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.