I have a an API callback function populating an array 'users', and when I console.log the array, all the elements are there, but when I try to get the length of the array, it is 0. Also accessing any part of the array it returns undefined. --> I get that this is asynchronous, however the suggested duplicate doesn't explain why the array is populating, and yet I can't access any part of it other than to log the entire array.
Can someone explain to me why? and offer some advice if i'm doing it all wrong? Thanks in advance
var users = [];
var twitchUsers = ["ogamingsc2","nightblue3","asiagodtonegg3be0", "freecodecamp", "brunofin", "cockadoodledo"];
buildURL = function(type, user){
var url = 'https://api.twitch.tv/kraken/' + type + '/' + user + '?callback=?';
return url;
}
function getRemainingData(element, index, array){
$.getJSON(buildURL("streams", element), function(streamData){
if(streamData.stream){
var game = streamData.stream.channel.game;
var status = streamData.stream.channel.status;
users.push({name:element, game:game, status:status, error:""});
}
else if(!streamData.stream && !streamData.error){
users.push({name:element, game:"", status:"", error:""})
}
if(streamData.error){
var error = streamData.error
users.push({name:element, game:"", status:"", error:error});
}
});
}
console.log(users); //returns array as attached below
console.log(users[0]); //returns unidentified
console.log(users.length); //returns 0