如何在 javascript/typescript 中等待异步超级函数?

问题描述 投票:0回答:1

在打字稿中,假设我有以下两个类:

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
,这进一步支持了我的理论,即它没有正确等待。

这是怎么回事?

javascript typescript asynchronous async-await promise
1个回答
-1
投票

看起来效果不错

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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.