Iterate over Array don't show all results

hi!
I stuck in the challenge “Twitch API”.

My loop didn’t show all results, but only the last one. What I do wrong?

var streamersArray = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var streamer;
var urlString = "https://wind-bow.gomix.me/twitch-api/streams/"
var newArray = [];

function twitchApi(){
  for (streamer of streamersArray) {
    var dataString = urlString+streamer+"?callback=?";
    newArray.push(dataString);
  };
  for (const i in newArray){
    $.getJSON(newArray[i], function(data){
      $
      if (data.stream == null){
        var user = "offline";
        $(".streamers").html(user);
      } else if (data.stream != null) {
        var user = data.stream.game
        $(".streamers").html(user);
      }
    });
  };
};

If somebote have asked for this yet, I;m really sorry :slight_smile:

Hi delta-foxtrot!

You are on the right track. The twitchApi function makes all the correct calls and retrieves the necessary information. Two things are messing things up, however.

The first thing was already addressed by randelldawson above.

The second, and this might not be a concern for the purposes of your program, but all of your asynchronous, $.getJSON requests are being made in parallel of each other.

Basically, your for-in loop loops across each .getJSON request instantly, passing in each value of newArray to the request. The for-in loop is synchronous while .getJSON takes some time to finish processing, hence its asynchronous nature. Upon the synchronous for-in loop’s execution, you essentially have eight .getJSON requests racing against each other to finish processing.

This means that the order by which you receive your data will differ each time you call the twitchApi function. If you want a consistent order, you will need to wait for each .getJSON request to finish before moving on the next newArray element and calling .getJSON once again.

Here is a suggestion to accomplish this with recursion. I also fixed the overwriting html, so hopefully this answers your question.

  function twitchApi(){
    for (streamer of streamersArray) {
      var dataString = urlString+streamer+"?callback=?";
      newArray.push(dataString);
    };
    
    twitchRequestAndAdd(newArray, 0)
  };
  
  function twitchRequestAndAdd(requestArray, i) {
    $.getJSON(requestArray[i], function(data){
      if (data.stream == null)
        { var user = "offline"; }
      else 
        { var user = data.stream.game }
        
      $(".streamers").append("<div class='streamer'>"+user+"</div>");
      
      if (requestArray[i + 1])
        { twitchRequestAndAdd(requestArray, i + 1); }
    });
  }

Thank you very much guys! :slight_smile: