0
this.reqURL = './appData/data.json';
this.req = new XMLHttpRequest();
        
this.req.open('get',this.reqURL);
this.req.responseType = 'json';
this.req.send();

this.resp = null;

this.req.onload = () => {
    this.resp = this.req.response;
}

console.log(this.resp);
null

I tried to make this.resp to be this.req.response However, it keeps returns null which is default value of it. I want this.resp to be this.req.response can I?

(Sorry for my bad english)

Mineppl12
  • 3
  • 1
  • `this.resp` is set asynchronously. You are using it synchronously. `this.resp` is set after the request finishes. Put the `console.log(this.resp)` underneath `this.resp = this.req.response;` and it won't be null. – Legend123 Mar 25 '21 at 03:11
  • It's because `this.resp` inside your arrow function doesn't refer to the same `this` as outside of it. They're not within the same scope. You need to create a variable _outside_ of your arrow function that refers to the correct `this`. Something like `const myThis = this;`. Then inside the arrow function, do `myThis.resp = this.req.response;` – icecub Mar 25 '21 at 03:12
  • @Evert Yup! it works now – Mineppl12 Mar 25 '21 at 03:45

0 Answers0