在打字稿中,假设我有以下两个类:
class X {
constructor() {
}
public async doSomething(): Promise<string> {
console.log('x')
return 'x'
}
}
class Y extends X {
constructor() {
super()
}
public override async doSomething(): Promise<string> {
console.log('y before')
await super.doSomething()
console.log('y after')
return 'y'
}
}
然后我运行以下命令:
const y = new Y()
y.doSomething()
我希望输出是:
y before
x
y after
但它是:
y before
x
几乎就好像
await super.doSomething()
没有在等待任何东西。我一直在研究它,发现如果我在 y.doSomething()
之后添加一些代码,承诺确实会解析并最终打印 y after
,这进一步支持了我的理论,即它没有正确等待。
这是怎么回事?
看起来效果不错
class X {
constructor() {}
async doSomething() {
console.log('x')
return 'x'
}
}
class Y extends X {
constructor() {
super()
}
async doSomething() {
console.log('y before')
await super.doSomething()
console.log('y after')
return 'y'
}
}
const y = new Y
y.doSomething()
原始
doSomething
可能会引发错误,因此没有'y after'
输出
class X {
constructor() {}
async doSomething() {
console.log('x')
throw 'e'
return 'x'
}
}
class Y extends X {
constructor() {
super()
}
async doSomething() {
console.log('y before')
await super.doSomething()
console.log('y after')
return 'y'
}
}
const y = new Y
y.doSomething()