I'm currently reading How do I return the response from an asynchronous call? and it seems to be related to why my code below is not working as expected. My console.log after the getJSON for loop is executing before the loop and therefore is returning null. The console.log within the getJSON loop is returning the objects pushed into the array.
After reading the referenced answers several times I'm more confused on how to implement the solution in a callback or promise. What do I need to do in my code below to either use a callback or promise so that the outer console.log returns data?
function channel() {
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var channelData = [];
for(var x = 0; x < channels.length; x++) {
$.getJSON(`https://api.twitch.tv/kraken/channels/${channels[x]}?callback=?`, function(data) {
console.log(data.display_name);
// console.log(data);
channelData.push( { display_name:data.display_name, logo:data.logo, url:data.url, game:data.game, status:data.status } );
console.log(channelData);
});
}
console.log(channelData);
}