[英]typescript awaiting an async function that returns a Promise<void>
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
關鍵字)控制台打印“完成”之前 Method() 中的所有操作都已完成?
是否保證
Method()
中的所有操作在.then()
回調打印“完成”之前完成
是的,通過使用.then()
方法。 await
關鍵字在這里無關緊要。 當你在做的時候,這很重要
await this.Method();
console.log('done');
(您可能應該這樣做)。
在調用不返回任何數據的異步方法時,我們是否必須使用
await
關鍵字?
是的,因為它們可能仍然會拋出錯誤,並且即使您不關心返回值,您也希望等待完成。 請參閱我可以在 nodejs (ES7) 中觸發並忘記 promise 嗎? 進行更多討論。
您可以簡單地執行以下操作:
caller = await this.Method().then(() => console.log('done'))
或者,如果您不需要使用結果
caller = this.Method()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.