0

I have a class, which stores specific values for that object such as name. But I can't get all the values at the beginning, I want to only get them when needed. So I added a getter function, which checks if the value has already been gotten and returns that. But if it hasn't (the first time), it needs to be retrieved from an async function. Is there anyway to do this with getters? It would have to not hold up the system process either as it's for a web server.

class a {

    get name () {
        if (this.storedName) return this.storedName;
        else asyncDBFunction((retreivedName)=>{
            return retreivedName;
        })
    }

    getValues () {
        return {name: this.name};
    }
};

var values = this.getValues();

Is there any way to do this, or do I just need to change my getter to a normal async function with a callback?

stackers
  • 2,701
  • 4
  • 34
  • 66
  • I don't think so, because then you'd have to write `await this.name` – Barmar May 20 '20 at 20:31
  • You can easily return a promise from a getter, but it's totally ugly. Also, you really shouldn't be doing side effects inside getters, surprising the unsuspecting developer who is using your class. (And no, a normal async function should return a promise, not take a callback). – Bergi May 20 '20 at 21:27

0 Answers0