0

Let's say I have some code similar to this:

let thing = null;
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
  thing = JSON.parse(this.responseText);
}
xhttp.open("GET", url);
xhttp.send();

console.log(thing.propertyOfThing);

This is not exactly my code, but it works for the purpose of this question. Anyway, the GET request works fine and thing gets set to the JSON object. However, when the code gets to the console.log statement, suddenly thing is null again and I get a NullPointerException (or at least the JavaScript equivalent of that) whenever I try to use properties of the JSON object.

Does anyone know why this is the case?

Rikudou
  • 145
  • 6
  • The `onload` function of the `XMLHttpRequest` is asynchronous. It needs to be used as a `Promise` or `async`/`await`. Have you tried this inside an `async` function? `const res = await fetch(), thing = await res.json(); console.log(thing.propertyOfThing);` I recommend `fetch` over `XMLHttpRequest`. – Mr. Polywhirl Dec 17 '21 at 19:21
  • The code to display console.log executes before the onload function call happens. Async. – James Dec 17 '21 at 19:59

0 Answers0