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 = "" + username +"?callback=?";
    $.getJSON(twitchURL, function(data){
    //create online and offline arrays based on twitch data
    if( {
    } else {
  //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(;
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?

If you read thedocumentation for let, you will see that it creates a block scope where var is only scoped to the nearest function block.

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.
if( {

” + and so on and so on …