Twitch Asynchronous API Call

Hi, I’m working on the Twitch API Project and am confused about how I can wait until the JSON calls are complete before my code continues. I am trying to set up an array of online usernames and an array of offline usernames from the multiple JSON calls so that I can order them. Before, the usernames would show up in a different order every time I loaded the page.

My problem now is that my arrays show up empty because I do not know how to wait for the JSON to populate the array before continuing.

Here is the function I’m having trouble with:
(usernames is just an array of usernames)

function getTwitch(usernames) {
  var online = [];
  var offline = [];
  for(var i = 0; i < usernames.length; i++){
    var username = usernames[i];
    var twitchURL = "https://wind-bow.glitch.me/twitch-api/streams/" + username +"?callback=?";
    $.getJSON(twitchURL, function(data){
    console.log(data);
    //create online and offline arrays based on twitch data
    if(data.stream) {
      online.push(username);
    } else {
      offline.push(username);
    }
    });  
  }
  console.log(online);
  console.log(offline);
  //printResults(online, offline, data);
}

The console shows my arrays online and offline as empty.

Any help would be very appreciated!! Thank you!

i changed your online.push to online.push(data.stream.channel.name);
and i get all channel names that are online.

This is a scoping issue with how you define var username inside a "for " loop, try defining it with “let username = username[i]” instead

1 Like

This worked for me. Why does the let keyword make such a difference?

When you execute console.log(online); console.log(offline); json isn’t gathered/arrived yet so console shows an empty array. To combat that, any displaying of said json you must be inside getJson. So …
prepend()/append()/html() and object property inside json request.
Example:
if(data.stream) {
$("#on").prepend(

” +
data.stream.property.property+ and so on and so on …
}