Sorry for my bad english. I am using a translator hoping you can understand me.
As I said in the header, when I try to create my html code in javascript the getJSON have not loaded the info needed to create the html code. I have read about it and I think is about async and I already tried to use callbacks but I couldn’t fix the problem.
I write my code here so you can check it.
$(document).ready(function(){
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
getChannelsNames();
function getChannelsNames(){
var myHtml = "", status = "Offline";
channels.forEach(function(channel, callback){
$.getJSON("https://wind-bow.glitch.me/twitch-api/streams/" + channel, function(json){
status = onlineStatus(json);
myHtml += infoChannels(channel, status);
}).fail(function(){
console.log("Error");
myHtml += infoChannels(channel, status);
});
});
$(".channels").html(myHtml);
}
function onlineStatus(json){
if(json.stream){
return json.stream.game;
} else {
return "Offline";
}
}
function infoChannels(channel, status){
return "<div class='row'><div class='col-12 col-md-4 bg-info'>" + channel + "</div><div class='col-12 col-md-8 bg-primary text-center'>" + status + "</div></div>";
}
});
The problem is in getChannelsNames() function. Notice at the end of this function I try to create a html code but the info is still not loaded because the getJSON is executed later. So $(".channels").html(myHtml);
doesn’t create the html code.
I hope you can understand my problem.