0

unable to get the async opertion done and sync its object/instance of the class.

class A {
    constructor() {
        this.init()
    }
    async init() {
        const p = new Promise((res, _) => {
            res(10)
        })
        this.data = await p
        console.log('this from A', this) // B { data: 10 }
        // want this data should update my child's 'this'
    }
}

class B extends A {
    constructor() {
        super()
    }
}

const b = new B()
console.log({ b }) // B {}

i did tried: Async/Await Class Constructor

but no one has a solution if class extends some other class.

what can be the best way to do so.

Ravi Singh
  • 1,049
  • 1
  • 10
  • 25

1 Answers1

2

The superclass shouldn't have a dangling promise like that, since outside consumers won't be able to see when the Promise resolves and act on it. Assign the promise to a property of the instance instead, so you can call .then on it.

class A {
    constructor() {
        this.init()
    }
    init() {
        this.pPromise = new Promise((res, _) => {
            res(10)
        })
        this.pPromise.then((result) => {
            this.data = result
            console.log('this from A', this) // B { data: 10 }
        });
    }
}

class B extends A {
    constructor() {
        super()
    }
}

const b = new B()
b.pPromise
  .then(() => {
    console.log({ b })
  });
  // .catch(handleErrors);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320