0
var preGameRequest = new XMLHttpRequest();
var preGameData;

preGameRequest.open("GET", "/matches/live.json");
preGameRequest.onload = function() {
    preGameData = JSON.parse(preGameRequest.responseText);
}
preGameRequest.send();
console.log(preGameData);   // main problem is here

Here is my code. I defined preGameData as global and tried to save /matches/live.json file's data into preGameData. And when I try to console.log(preGameData) from outside of the scope (like in the code section) I get 'undefined' as a return. And if I try to console.log(preGameData) from inside of the scope it works. I don't really know what's going on.

1 Answers1

0

That code should work:

preGameRequest.onload = function() {
    preGameData = JSON.parse(preGameRequest.responseText);
    console.log(preGameData);
}

The reason: is that preGameRequest.send() function operates asynchronous.

When the browser tries to execute console.log() (in your example), the http response is not recieved yet, and the variable is really undefined.

But if you place console.log() inside of the handler (as in my example), it would be executed at moment, when the response is already recieved (straight in the onload() handler). And that's why the variable preGameData would be defined already.

Ivan Litskevich
  • 106
  • 1
  • 5