I have problems with TwitchTv api project with getJSON and async

I have problems with TwitchTv api project with getJSON and async
0

#1

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.


#2

Add a console.log(myHtml) between channels.forEach() and $(".channels").html(myHtml);
If your not getting anything, chances is that $(".channels").html(myHtml); did not wait until the loop is complete. You’ll have to work around with putting the code inside $.getJSON() and tell to append for each loop.


#3

It works inside the getJSON but I don’t think that be the right way because it updates the content in every forEach. It worked with $ajax instead of getJSON and I had to use async:false. I would like to do it with async because in the future maybe I will need to know how to do it in that way.


#4

What you have to do is to perform all the actions inside the getJSON rather to call out functions like onlineStatus() and infoChannels()


#5

And Do I have to perform $(".channels").html(myHtml); inside getJSON too?? I can do it but is this the right way to do it??


#6

If your code is still like it is above, then yes, you need to perform the $(".channels").html(myHtml); inside the $.getJSON callback function.