0

I'm pinging the twitch API with a list of users, and trying to add the Json from each to an array. The for loop iterates through the list of users and returns the json for each call with each individual name. If I put the console.log(arr) inside the for loop, I get 8 logs each with an additional users Json tacked on, which I would expect. However, when I call console.log(arr) outside of the for loop, it returns an empty array. I setup the variable before going into the for loop, so it should be a global variable, no? Why is the information lost after the for loop?

var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]

var headers = {
  'Client-Id': 'xxxxxxxxxxxxxxxxxxxxxxxxx'
}

var arr = [];

for (i = 0; i < users.length; i++) {
  var url = "https://api.twitch.tv/helix/users?login=" + users[i];
  fetch(url, {headers})
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    arr[i] = myJson;
  });
}
console.log(arr);
Sphinx
  • 10,519
  • 2
  • 27
  • 45
Cdhippen
  • 615
  • 1
  • 10
  • 32
  • See answer linked above, is the same issue. The problem is not hat it's inside the `for`, the problem is that it's inside the callback function and it's executed after the last line. – raul.vila Apr 18 '18 at 22:42

1 Answers1

0

console.log(arr) should be before the last bracket rather than after.

  • Why shouldn't I be able to call it from anywhere in the script? If it's a global variable should I not be able to reference it elsewhere? – Cdhippen Apr 18 '18 at 22:53
  • Feargal, that wouldn't work either, the assignment is done inside an asynchronous callback function. @Cdhippen see related questions linked in comments, you'lll find an explanation there. – raul.vila Apr 18 '18 at 22:56
  • Nevermind, I read the solution linked above, and that provided the context that I needed for asynchronous vs synchronous. Thanks for the help! – Cdhippen Apr 18 '18 at 22:56
  • Now I'm confused again, I put it inside the last bracket, and now it just returns 8 empty arrays – Cdhippen Apr 18 '18 at 22:57
  • Also want to add that, since you are looping to make multiple async calls, you could instead push the result of each fetch call into the array, then use Promise.all(arr).then and console log within that 'then' block.' If, that that point, you are still not getting the intended result, it may be completely unrelated to your handling of promises. – Devin Fields Apr 18 '18 at 23:58
  • I opened a new question with more details with what I have tried now that I kind of know what a promise is: https://stackoverflow.com/questions/49910878/im-trying-to-understand-how-to-use-promises-in-javascript-but-my-script-never – Cdhippen Apr 19 '18 at 00:27