0

I am a beginner in JavaScript, so please forgive me my lack of knowledge.

I would like to initialize an object with the attributes of a custom JavaScript Class in two steps.

First: initialize some attributes based on arguments in constructor function

class Test {
    constructor(a, b, url) {
            
      this.a = a;
      this.b = b;
      this.url = url;
}


Second: request the url and assigning the response data to some more attributes

class Test {
    constructor(url, a, b) {
      
      this.a = a;
      this.b = b;
      this.url = url;
      
      fetch(this.url)
        .then(response => response.json())
        .then((data) => {
          this.dataA = data;
          this.dataB = data.b;
          this.dataC = data.c;
        })
    }
  }

Somehow the attributes initialized during the fetch function are not accessible from outside. For example, if I call the attributes in the constructor function, I just receive an undefined object.

class Test {
    constructor(url, a, b) {
      
      this.a = a;
      this.b = b;
      this.url = url;
      
      fetch(this.url)
        .then(response => response.json())
        .then((data) => {
          this.dataA = data;
          this.dataB = data.b;
          this.dataC = data.c;
          console.log(this.dataA, this.dataB, this.dataC) // data accessible
        })

    console.log(this.dataA, this.dataB, this.dataC)// data undefined
    }
  }

Anybody having an idea, why it is like that? Maybe because the request is asynchronous? Also I am really not sure, if it is usual to make requests in a constructor function in general. What do you think?

Thanks in advance!

isherwood
  • 58,414
  • 16
  • 114
  • 157
WillG
  • 41
  • 7

0 Answers0