Problem with .html() function

Problem with .html() function
0

#1

Hello, I need some help… What is wrong with this code? " $(".streams").html(tag);" line only executes inside my ajax function, and the output is curved a little bit. But i want it to be executed outside forEach function and ajax function as well

$(document).ready(function() {
  
  var api = "https://wind-bow.gomix.me/twitch-api/streams/";
  var streamers = ["ESL_SC2", "freecodecamp", "noobs2ninjas", "RobotCaleb"];
  var tag = "";
 
  streamers.forEach(function(val) {
    $.getJSON(api + val + '?callback=?', function(data) {
        if (data.stream === null) {
          tag += "<div class='stream'>" + "<b>" + val + "</b>" + "<div class='status'><p>Offline</p></div>";
        }
        else  {
          tag += "<div class='stream'>" + "<b>" + val + "</b>" + "<div class='status'><a href='" + data.stream.channel.url + "' target='_blank'>" + data.stream.channel.status + "</a></div>";
        }
     });
  });
  $(".streams").html(tag);
});

#2

Hey. The $.getJSON method is asynchronous; meaning that javascript won’t wait for the request to finish before passing to the next line of code (in your case, $(".streams").html(tag);). So, you need to have your logic inside the success callback of the method.

If you really, really want to wait for all the requests to be finished and call the .html() outside of the loop, then you could use $.when() and .apply() passing it an array of promises; $.when() expects promises as parameters so passing it the array wouldn’t work; we use .apply() to execute $.when() on each element of the array:

  var api = "https://wind-bow.gomix.me/twitch-api/streams/";
  var streamers = ["ESL_SC2", "freecodecamp", "noobs2ninjas", "RobotCaleb"];
  var tag = "";
  var requests = []; // Requests array
 
  function getStreams(val) { // Returns a promise
    return $.getJSON(api + val + '?callback=?').done(function(data) {
      if (data.stream === null) {
        tag += "<div class='stream'>" + "<b>" + val + "</b>" + "<div class='status'><p>Offline</p></div>";
      } else {
        tag += "<div class='stream'>" + "<b>" + val + "</b>" + "<div class='status'><a href='" + data.stream.channel.url + "' target='_blank'>" + data.stream.channel.status + "</a></div>";
      }    
    });
  } 
  streamers.forEach(function(val){
    requests.push(getStreams(val)); // Pushes promises into the requests array
  });

  $.when.apply($, requests).done(function(){ // Waits for all the requests to be done. Same as $.when(requests[0], requests[1], requests[2], ...)
    $(".streams").html(tag);
  });