Hello there. I’m on the twitch.tv json api challenge. My problem is apart from the last string in the array, all previous string’s api calls are cancelled. It says “Provisional headers are shown” in the console. I’m using a forEach function to iterate through the array. I wanted to see all the received json in the console.
Here’s the code:
var xhr = new XMLHttpRequest();
var array = [“ESL_SC2”, “OgamingSC2”, “cretetion”, “freecodecamp”, “storbeck”, “habathcx”, “RobotCaleb”, “noobs2ninjas”];
array.forEach(function(stream){
var url = “https://wind-bow.glitch.me/twitch-api/streams/” + stream;
xhr.open(“GET”, url, true);
xhr.onload = function(){
if(xhr.status == 200){
var data = JSON.parse(this.response);
}
else {
console.log(“error”);
}
console.log(data);
}
xhr.send();
});
The problem is, you’re overriding the xhr request on every iteration with a new call to the next streamer and because ajax calls are asynchronous, when they are processed only the last stream in the list successfully completes.
Easy fix, try moving the declaration of the xhr variable inside the forEach callback, that way, each request gets it’s own request object.
var array = ['ESL_SC2', 'OgamingSC2', 'cretetion', 'freecodecamp', 'storbeck', 'habathcx', 'RobotCaleb', 'noobs2ninjas'];
array.forEach(function(stream) {
var xhr = new XMLHttpRequest();
var url = 'https://wind-bow.glitch.me/twitch-api/streams/' + stream;
xhr.open('GET', url, true);
xhr.onload = function() {
if (xhr.status == 200) {
var data = JSON.parse(this.response);
} else {
console.log('error');
}
console.log(data);
}
xhr.send();
});
Thank you @joesmith100!
Your code works wonderfully, now i could finally see all the returned json. Regarding the overriding xhr part, is it because the forEach method is changing the url of xhr request with every iteration? Like when the request is still waiting for a response, its url gets changed, and only when the forEach method ends on the last sting in the array does the xhr request fire successfully without interference?
Would storing the parsed json in another array for later access be a safe way of using data? In the previous projects i wrote all of my code in the xhr.onload function. I saw an answer on stackoverflow use this and I’ve been wondering if its valid or not.
Kind of, each request is still technically sent, however, when you call open again, it aborts the previous request and starts a new one, hence the cancelled debugger statements. See here.
The problem I see with that solution however is that it it runs each request in succession and doesn’t make another request until the previous one is complete. If one request takes along time to complete for some reason then you the user will perceive the delay which is never good! Of course, if you really need all the data to be loaded before you process it than that isn’t a bad solution, however, if you don’t, I’d just stick to processing each response as it comes in.