【发布时间】:2021-08-24 03:25:41
【问题描述】:
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() 内的所有操作都已完成?
【问题讨论】:
-
你为什么要把
async和new Promise()混在一起?如果你return new Promise(...),这可能会达到你的预期,你不需要将Method定义为async -
这是返回 promise
的方法示例,例如更新或删除 firebase 实时数据库中的数据。使用异步或返回新的promise都返回promise ,我的问题是我们是否必须等待一个返回promise 的方法
标签: javascript typescript asynchronous async-await promise