[英]async/await with super constructor
無法完成異步操作並同步其 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 {}
我確實嘗試過: 異步/等待 Class 構造函數
但是如果 class 擴展了其他一些 class,沒有人有解決方案。
最好的方法是什么。
超類不應該有這樣的懸空 promise,因為外部消費者將無法看到 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.