I have a script that sets a set number of usernames, and then for each username, runs a fetch request to twitches API endpoint to get the Json information for each user. I then wanted to put that information into an array for later use, and found out I had to use promises, which I never worked with before. I read through this: https://developers.google.com/web/fundamentals/primers/promises and this: https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md and I read Felix Kling response here: How do I return the response from an asynchronous call? and I'm still having trouble understanding exactly what goes where and what does what. This is what I have so far:
var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]
var arr = [];
var headers = {
'Client-Id': 'xxxxxxxxxxx'
}
var promise = new Promise(function usersJson(callback) {
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.push(myJson);
})
callback(arr);
};
})
promise.then(function(result) {
console.log(result);
})
and from what I understand, this should be running through each endpoint, pushing the data to my array variable, and then once the whole things is "fulfilled" it should call the 'then' thing with my promise variable to console.log my array. All I get is a blank array and I'm really not sure what I'm doing wrong. If I put the console.log(arr) in after the arr.push(json), I get 8 arrays returned, each with the next response body tacked on, so I know the call is working, I just can't get it to stick in my array.