Asynchronous javascript/ajax problems

Status
Not open for further replies.

NCPar8hd

Ars Tribunus Militum
2,351
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.
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/
 

krimhorn

Ars Legatus Legionis
39,865
Ajax is asynchronous by design so any code outside of the .done callback continues to be executed normally. The correct way to do this is to either add your function call within the .done callback or I believe you can hang another .done callback off of the first to make your code more readable and call the function there. The second won't be executed until the first is completed.
 

krimhorn

Ars Legatus Legionis
39,865
Ajax is asynchronous by design so any code outside of the .done callback continues to be executed normally. The correct way to do this is to either add your function call within the .done callback or I believe you can hang another .done callback off of the first to make your code more readable and call the function there. The second won't be executed until the first is completed.

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) => { 
        //your processing code here           
       })
       .done(() => {
         displayChannels();
       });
  });
};

function displayChannels() {
  channelInfo.forEach((channel)=>{
    $('#list').append(channel);
  });
}


getDataFromTwitch();
 

rabish12

Ars Legatus Legionis
16,983
Yeah, I knew ajax was async by design, but I was hoping there was some trick to work around it. I figured out a way to do what I wanted, so all is not lost. Thanks for your help.
There's "tricks", but they kind of involve completely changing the way that you're writing your code to approach the problem. If you break up the steps into smaller individual functions then you can use the Promise API (which jQuery supports) to chain them together a bit more cleanly. It's not especially easy to get into that mindset if you haven't dealt with it before though, so you might be better off just doing it the way that you're doing it now.
 
Status
Not open for further replies.