-2

I have a simple class:

class Build {
    dataFetched = {};

    constructor(id = '') {
      this.id = id;
    }
    
    getData(){
        return request({
            some request
        }).then(({ data }) => {
            this.dataFetched = {...data};
        }).catch(({e}) => {
            console.log(e);
        });
    }

   showData(){
        return this.dataFetched;
    }
}

in a different file i am trying to create an object and call getData as well as showData

 let test = new Build(input_data);
 test.getData();
 test.showData(); 

this returns an empty object, but if method showData just returns "this" the dataFetched property is filled with data from the request.

Not sure what is going on, and would grealty appreciate some help/clarification

  • when you call `showData` the promise is not yet been resolved – Alberto Sinigaglia Jun 14 '21 at 14:39
  • @AlbertoSinigaglia but when i return "this" instead of "this.dataFetched" dataFetched is populated? why is that – asynctomas Jun 14 '21 at 14:41
  • @asynctomas because the dev console is magic (it loads in data as the object is when you expand it, not when you logged it) – Kevin B Jun 14 '21 at 14:44
  • Requests are asynchronous meaning they need time to send the request before they can receive the fetch data. When you run this code at all at once, you are calling `showData` before the request(...).then had time to process your HTTP request. be why you are getting the empty object. When you manually run `test.showData()` after some time has passed, the request completed so you get the data you expect. You see the `.then` function that adds the data to dataFetched? That function needs time beofre running. It doesn't get run right away – Roger Z Jun 14 '21 at 14:45

1 Answers1

-1

You need to await getData() before calling showData as it returns a promise

let test = new Build(input_data);
await test.getData();
console.log(test.showData()); 

This must be within an async function.

The other option is to chain another then on to the return - this doesn't need to be within an async function

let test = new Build(input_data);
test.getData().then( () => console.log(test.showData()));
Jamiec
  • 133,658
  • 13
  • 134
  • 193