正在等待返回 Promise<void> 的异步函数的打字稿

时间:2021-06-07 01:12:23

标签: javascript typescript asynchronous async-await promise

Method() {
    // simulating a method of a third-party library that returns Promise<void>
    return new Promise(() => {
      // some time-consuming operations
    }).then(() => console.log('end'))
  }

在调用不返回任何数据的异步方法时,我们是否必须使用 await 关键字?

await this.Method().then(() => console.log('done'))
// or
this.Method().then(() => console.log('done'))

对于这个例子,是否保证在两种情况下(使用和不使用 await 关键字)在控制台打印“done”之前完成 Method() 中的所有操作? >

2 个答案:

答案 0 :(得分:1)

<块引用>

是否保证Method()内的所有操作在.then()回调打印“done”之前完成

是的,因为使用了 .then() methodawait 关键字在这里无关紧要。什么时候做很重要

await this.Method();
console.log('done');

(你probably should)。

<块引用>

在调用不返回任何数据的异步方法时,我们是否必须使用 await 关键字?

是的,因为它们可能仍然会抛出错误,即使您不关心返回值,您也想等待完成。有关更多讨论,请参阅 Can I fire and forget a promise in nodejs (ES7)?

答案 1 :(得分:0)

您可以简单地执行以下操作:

caller = await this.Method().then(() => console.log('done'))

或者,如果您不需要使用结果

caller = this.Method()
相关问题