I'm using ajax to get data from an api. I am storing the data in an array inside the ajax call. I would like to use a separate function to display the data, but the function gets called before the ajax call is finished. I have tried different combinations of async/await and promises to make the display function wait until ajax is finished to run, but I have not figured it out yet. I can display the data from inside the ajax call, but that is less than ideal. Any help would be greatly appreciated.
Full code here:
https://codepen.io/jasoncoburn/pen/jYmaMq/
Code:
const channels = [ "streamerhouse",
"OgamingSC2",
"cretetion",
"freecodecamp",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas",
"cohhcarnage"];
let channelInfo = [];
const list = document.getElementById('list');
const ajaxOptions = {
callback: 'callback',
dataType: 'jsonp'
};
function getDataFromTwitch() {
channels.forEach((channel)=> {
let url = 'https://wind-bow.gomix.me/twitch-api/';
$.ajax(url+'streams/'+channel, ajaxOptions)
.done((data) => {
if (data.stream === null) {
//If the stream isn't live, get data from the channels endpoint
$.ajax(url+'channels/'+channel, ajaxOptions)
.done((data)=> {
let html = `<li class="offline"><img src="${data.logo}"/> <p class="name"><a href="${data.url}">${data.name}</a></p><p>Offline</p></li>`;
channelInfo.push(html);
//$('#list').append(html);
}).fail(()=>{
alert('There was a problem getting the data. Pleae retry.');
});
} else {
//use data from streams endpoint if channel is live
let html = `<li class="online"><img src="${data.stream.channel.logo}"/> <p class="name"><a href="${data.stream.channel.url}">${data.stream.channel.display_name}</a></p>
<p class="game">Now Streaming: ${data.stream.channel.game}</p><p class="viewers">Viewers: ${data.stream.viewers}</p></li>`;
channelInfo.push(html);
//$('#list').append(html);
}
}).fail(() => {
alert('There was a problem getting the data. Please retry');
});
});
};
function displayChannels() {
channelInfo.forEach((channel)=>{
$('#list').append(channel);
});
}
getDataFromTwitch();
//displayChannels();
Full code here:
https://codepen.io/jasoncoburn/pen/jYmaMq/