0

I have a large script which performs a load of Promises and Async calls so I created a new class which I started moving promise functions into. But i am now struggling to have the class properties initialize.

class MyClass {
    constructor(id) {
        this._id = id
        this._thing = []
    }

    getThing {
        return this['_thing']
    }

    async init() {
        this._thing = this.requestThing(this['_id']) 
    }

    requestThing(id) {
        return new Promise((resolve) => {
            // Make request using id
            resolve(response);
        })
    }
}

So I was thinking of something like this

const init = async () => {
    let myClass = await new MyClass(123)
    await myClass.intialise()
    let test = myClass.getThing()
}

init()

But I seem to be getting errors. At this point my code is pretty hard to debug (or rewrite to make a simple test - hence the refactor) as I am using lots of Promises and async functions.

Is this the correct way to initialize a class which needs to make async calls to set its properties?

myol
  • 8,857
  • 19
  • 82
  • 143
  • @slebetman If you are going to mark this question duplicate and then link to your own answer could you please expand your answer? Trying to use the factory pattern I cannot 'doSomeAsyncStuff' in the factory as I keep getting method is undefined – myol Apr 14 '18 at 04:59
  • Define `requestThing` as either a regular function outside the class or a static member in the class (in which case you would call it `MyClass.requestThing()` instead of using `this`. – slebetman Apr 14 '18 at 12:24
  • I added the long explanation in the answer itself but it really has nothing to do with async. It actually merits its own question – slebetman Apr 14 '18 at 12:38
  • @slebetman thank you very much for the extended explanation, I didn't realize I had stumbled onto an XY problem about `this` and static methods. Your original answer pointed me in the right direction about using static methods but your extended explanation confirmed it. – myol Apr 15 '18 at 03:34
  • You're welcome. Dynamic and functional languages tend to have simple syntax and fewer rules compared to static languages but they also tend to have more things that arise out of interactions between different rules. If you think about it it would seem logical but behaviours like this aren't documented until someone stumbles on them and ask questions online – slebetman Apr 15 '18 at 07:52

0 Answers0