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!