I’m having trouble with a JavaScript loop when working with a streaming platform’s API. My code checks if streamers are live or offline. For live streamers, I use one API endpoint. For offline streamers, I make another API call to get their channel info.
The problem is weird. When streamers are offline, the loop only processes the last streamer from my array instead of all the offline ones. I can’t figure out why this happens.
var makeRequest = function(endpoint, callback) {
var request = new XMLHttpRequest();
request.open("GET", endpoint, true);
request.onload = function() {
if(request.readyState == 4 && request.status == "200") {
callback(JSON.parse(request.responseText));
}
};
request.send();
};
var streamers = ["ninja", "shroud", "pokimane", "xqc", "tfue", "sodapoppin"];
var api_key = "abc123def456ghi789jkl";
var container = document.getElementById("streamer-list");
var elements = [];
for(var j = 0; j < streamers.length; j++) {
var live_url = "https://api.example.tv/v1/live/" + streamers[j] + "?key=" + api_key;
var profile_url = "https://api.example.tv/v1/users/" + streamers[j] + "?key=" + api_key;
makeRequest(live_url, function(data) {
if( data["live_stream"] !== null ) {
elements[j] = document.createElement("div");
elements[j].className = "stream-card";
elements[j].innerHTML = "<a href='" + data.live_stream.profile["link"] +
"'><img src='" +
data.live_stream.profile["avatar"] +
"' /><h3>" +
data.live_stream.profile["username"] +
"</h3><span>" +
data.live_stream["category"] + "</span></a>";
container.appendChild(elements[j]);
} else {
makeRequest(profile_url, function(profile) {
elements[j] = document.createElement("div");
elements[j].className = "stream-card";
elements[j].innerHTML = "<a href='" + profile["link"] +
"'><img src='" +
profile["avatar"] +
"' /><h3>" +
profile["username"] +
"</h3><span>Not Live</span></a>";
container.appendChild(elements[j]);
});
}
});
}
Any ideas what’s causing this behavior?