I have a procedure which makes a few ajax requests in a loop, each time appending the data to a global array.
After the procedure ends, I try to output the global array's contents on the console and it works fine: I can see a list of objects in Chrome console.
But right in the next line I try to print the length of that array, but it shows 0. I am also unable to access any element of the array using an index.
I know that JS will sometimes execute the statements outside the AJAX request while the request is finishing, but that's not what's happening here. In my case the AJAX requests are completed, and successfully fill the pictures array with the data I need. And yet the next line is showing a length of zero.
Here's the code snippet:
var venues = **some array**
var pictures = [];
function() {
// Get 2 picture urls for each venue
for(var i=0; i<venues.length; i++) {
var venue = venues[i];
var new_url = **valid url**
$.ajax({
url: new_url
}).done(function(data) {
var pics = data.response.photos.items;
pictures.push(pics[0]);
pictures.push(pics[1]);
}).fail(function() {
console.log('Images failed!');
});
}; //loop ends
console.log(pictures); <-- Shows a legit array of all the objects I expected
console.log(pictures.length); <-- Shows zero!!!