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?