Remove function declaration from loop - XHR/Async

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!

XHR isn’t the way to do AJAX in vanilla JS anymore. forEach is definitely the way to go, but to handle the requests you should use the fetch api. Not only will this be easier to read than XHR requests, you’ll be able to pull your functions outside of your loop.

1 Like

Cool! I had never heard of fetch api so I will look into it. It is great that it returns a Promise as well, so I can work with those!

1 Like