I am working on the twitch.tv API project, and decided to use vanilla JS to help me.
One issue I am facing is I am making the async requests inside of a for loop, and therefore each time I am declaring the function for .onload
What is the best way to factor the function outside? If I pull it out directly it doesn’t work. I know (assume) it’s an async issue.
Here’s my code:
const url = "https://wind-bow.glitch.me/twitch-api/streams/";
const userArr = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas","dreamhackhs"];
for (var i in userArr){
let user = userArr[i];
let request = new XMLHttpRequest();
request.open('GET',url+user);
request.responseType = 'json';
request.send();
request.onload = function(){
item = request.response;
var data = JSON.stringify(item);
var streams = document.createElement("p");
streams.innerHTML= data + "<br>";
console.log(streams);
document.body.appendChild(streams);
};
}
EDIT I’ve gotten a little farther, but still declaring a function each time
const url = "https://wind-bow.glitch.me/twitch-api/streams/";
const userArr = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas","dreamhackhs"];
for (var i in userArr){
let user = userArr[i];
let request = new XMLHttpRequest();
request.open('GET',url+user);
request.responseType = 'json';
request.send();
request.onload = function(){make(this.response)};
};
function make(item){
var data = JSON.stringify(item);
//console.log(data);
var streams = document.createElement("p");
streams.innerHTML= data + "<br>";
//console.log(streams);
document.body.appendChild(streams);
};
EDIT2 Got it done with a .forEach on the array, but still curious!