【问题标题】:async/await with super constructor带有超级构造函数的异步/等待
【发布时间】:2026-02-23 14:30:01
【问题描述】:

无法完成异步操作并同步其类的对象/实例。

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 {}

我试过了:Async/Await Class Constructor

但是如果类扩展了其他类,没有人有解决方案。

最好的方法是什么。

【问题讨论】:

    标签: javascript oop inheritance


    【解决方案1】:

    超类不应该有这样的悬空承诺,因为外部消费者将无法看到 Promise 何时解决并采取行动。将 Promise 分配给实例的属性,以便您可以在其上调用 .then

    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);

    【讨论】: