1

How to access the returned data from getData() in printData? Can I store the data in a global variable?

The following is what I have as an example:

home.js

export class Home {
    //d;
    constructor() {
        this.printData();
    }
    getData() {
        httpClient.fetch('example.com/api/v')
            .then(response => response.json())
            .then(data => {
                return data;
                //this d = data;
            });
    }
    printData() {
        var data = this.getData();
        console.log(data.name);
        //console.log(this.d.name);
    }
}
Adn
  • 135
  • 1
  • 13
  • 1
    You need to learn how promises work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developers.google.com/web/fundamentals/primers/promises – Jeff G Jan 27 '20 at 21:17
  • 1
    @JeffG I am having trouble understanding promises and how it is related to what I have. Could you explain it for me? – Adn Jan 27 '20 at 22:32
  • 1
    Try this: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – Jeff G Jan 28 '20 at 16:11

0 Answers0