Hi Guys,
I have been trying to work with two AJAX functions so that I can retrieve two JSON objects. As “.getJSON(…)” function is asynchronous my website is loading the channels of “twitch.tv” project randomly( and incorrectly too) . I have tried lots of methods like closure functions, callback functions, included the asynchronous functions within “when(…)…done(…)/ when(…)…then(…)” after reading lots of topics from stackoverflow and other websites. I’m still a novice and didn’t really understood those posts. I would be glad if someone can correct my code or help me with the code. Link:https://codepen.io/saicharan123/pen/VzXmwr?editors=1111 Following is the js code:
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", `"RobotCaleb", "noobs2ninjas"];`
$(document).ready(function(){
var streamObj, channelObj, channelUrl, streamUrl;
for(var x = 0 ; x < channels.length; x++){
channelUrl = "https://wind-bow.glitch.me/twitch-api/channels/"+channels[x];
streamUrl = "https://wind-bow.glitch.me/twitch-api/streams/"+channels[x];
$.when(
$.getJSON(channelUrl, function(data) {
channelObj = data;
}),
$.getJSON(streamUrl, function(data) {
streamObj = data;
})
).done(function() {
if(!streamObj["stream"]){
$("channel").append("<img src = " + channelObj["logo"]+"</img><br/><br/>");
$("#channel").append("<img src = "+channelObj["logo"]+"></img><a href = "+channelObj["url"]+" class = 'text'>"+channelObj["display_name"]+"</a><span class='online'>Currently Streaming:"+streamObj["game"]+channelObj.status+"</span><br/><br/>");
}
else{
$("#channel").append("<img src = "+channelObj["logo"]+"></img><a href = "+channelObj["url"]+" class = 'text'>"+channelObj["display_name"]+"</a><span class='offline'>Status:Offline</span><br/><br/><br/>");
}
});
}
})