Twitch Viewer - XmlHttpRequests

Twitch Viewer - XmlHttpRequests
0

#1

Hi fellow campers, so I am here once again reaching out for you advice. More precisely, explanation.
I figured the problem out myself but I don’t know why it works the way it works and I’d like to know.

So here’s the working code:

var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "sodapoppin"];
var xhttps = new Array();
var xhttps_responses = new Array();

for(var x = 0; x < streamers.length; x++){
    
    xhttps[x] = new XMLHttpRequest();
    console.log(xhttps[x]);
    
    xhttps[x].open('GET', "https://wind-bow.glitch.me/twitch-api/streams/" + streamers[x]);
    
    xhttps[x].onreadystatechange = readyStateHandler(xhttps[x]);
    
    xhttps[x].send();
  

}

function readyStateHandler(xhttp){
    
    return function(){
        if(xhttp.readyState == 4){

            console.log(xhttp.responseText);

        }
    }
    
}

And here is the code that doesn’t work:

var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "sodapoppin"];
var xhttps = new Array();
var xhttps_responses = new Array();

for(var x = 0; x < streamers.length; x++){
    
    xhttps[x] = new XMLHttpRequest();
    console.log(xhttps[x]);
    
    xhttps[x].open('GET', "https://wind-bow.glitch.me/twitch-api/streams/" + streamers[x]);
    
    xhttps[x].onreadystatechange = readyStateHandler(xhttps[x]);
    
    xhttps[x].send();
  

}

function readyStateHandler(xhttp){
    
    if(xhttp.readyState == 4){

        console.log(xhttp.responseText);

    }
    
}

The only difference is that the onreadystatechange callback returns a function or executes a function.
Where’s the difference?
Thank you for explanation of any kind! :slight_smile:


#2

The onreadystatechange property should contain the event handler to be called when the readyState event is fired. Thus, it’s value should be set to a function that would be executed once the event is fired.

xhttps[x].onreadystatechange = readyStateHandler(xhttps[x]);

In the above snippet, the onreadystatechange property is set to the value returned by the function readyStateHandler.

readyStateHandler is executed at the time of assignment, that is prior to sending the request to the API.

For the code that doesn’t work, when readyStateHandler, the value of readyState will be 1 as the connection has just been opened, but not sent, so the if condition evaluates to false and the function returns null, which is set to the onreadystatechange property.

But, in the case where you return a function, the onreadystatechange property contains a function, and this function will be executed once the readyState value for the corresponding xhr object changes.

You can refer the MDN link for onreadystatechange.


#3

Thank you very much :slight_smile: