0

I've been building a project in codepen for FreeCodeCamp and this one part of the project has me stumped.

It seems like the code should work, I am getting the correct results when I console.log the results, but when they render on the page, they come up as undefined.

Could anyone explain why I am running into this issue? I feel like I've run into it a lot and maybe I am missing some fundamental concept.

Here is my codepen

Here is my JS:

$(document).ready(function(){

  var streams = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "habathcx", "RobotCaleb", "noobs2ninjas"],
      url = 'https://wind-bow.gomix.me/twitch-api/',
      streamerInfo = [];

  for(var i = 0; i < streams.length; i++){
    var streamer = streams[i];
    getInfo(streamer, i);
  }

  function getInfo(streamer, i){
    $.ajax({
      dataType: 'json',
      type: "GET",
      url: url + 'channels/' + streamer + '?callback=?',
      success: function(data){
        // console.log(data);
        createHTML(data, i);
      },
      error: function(data){
        console.log('Fail');
        $('#streamers-container').html("<h2>Error. Please Refresh Page or Try Again Later</h2>");
      }
    });
  }

  function createHTML(data, i) {
    var status = "Offline";
    function displayStatus(i){
        $.ajax({
        dataType: 'json',
        type: "GET",
        url: url + 'streams/' + streams[i] + '?callback=?',
        success: function(data){
          if (data.stream !== null) {
            status = data.stream.game;
            return status;
          } else {
            return status;
          }
          }, error: function(data){
            console.log('Fail');
            $('#streamers-container').html("<h2>Error. Please Refresh Page or Try Again Later</h2>");
          }
        });
      }

    document.getElementById('streamers-container').innerHTML +=
      '<div class="streamer-block">' +
        '<div class="streamer-logo">' +
          '<img class="image-responsive" src="' + data.logo + '">' + 
        '</div>' +
        '<div class="streamer-name">' +
          '<a href="' + data.url + '">' +
            data.display_name +
          '</a>' +
        '</div>' +
        '<div class="streamer-status">' +
          displayStatus(i) +
          // data.status +
        '</div>' +
      '</div>';
  }

//   End of script
});
PavelCreates
  • 13
  • 1
  • 6
  • In your `displayStatus` function you have an ajax call with `$.ajax`. Ajax is asynchronous, and you can't return from it, see the duplicate for suggestions on how to solve it. – adeneo Jul 25 '17 at 00:05
  • oh boy, you're mixing your sync and async code together. – Bamieh Jul 25 '17 at 00:07
  • As above comment Ajax is Async which will not wait for the response... You can try something like this https://codepen.io/anon/pen/GvRaYP – Muthu Kumaran Jul 25 '17 at 00:24

0 Answers0