For the last couple of hours, I have been trying to solve a FreeCodeCamp challenge (specifically, http://www.freecodecamp.com/challenges/zipline-use-the-twitch.tv-json-api) in which we are supposed to get info from Twitch, via JSON. I have been trying to get some info from a $.getJSON request. I realized the issue with async calls, but I seem to still be running into some issues. Note: users is simply an array of Twitch users.
My Code:
var users = ["freecodecamp", "storbeck", "terakilobyte", "srkevo1", "habathcx","RobotCaleb","comster404","brunofin","thomasballinger","noobs2ninjas","beohoff"];
var online=[];
var offline= [];
for(var i =0; i < users.length; i++){
var StreamURL = "https://api.twitch.tv/kraken/" +"streams/" + users[i] + "?callback=?";
getOnline(StreamURL).then(function(returndata){
online.push(returndata.data);
console.log(online);
});
}
function getOnline(val){
return $.getJSON(val).then(function(data){
return{
stream:data.stream,
data:data._links
}
});
}
Everything seems fine when I log the users in the actual for loop (i.e. the console.log of online successfully gets the info from all the users) but when I exit the loop, and print the same thing, I get an empty array. How do I ensure that this data is preserved?