[英]What's a clean way to share async function response in Javascript?
我有與此類似的異步功能:
class ArticleParser() {
_title;
async genTitle() {
if (!this._title) {
this._title = await takesALongTime();
}
return this._title;
}
}
如果genTitle
在第一個調用完成之前被多次調用,它將多次調用takesALongTime
。 我希望所有對genTitle
調用都共享相同的返回承諾。 有沒有一種干凈/簡單的方法?
這是一個可行的解決方案,但看起來很混亂:
class ArticleParser() {
_title;
_genTitlePromise;
async _genTitle() {
this._title = await takesALongTime();
}
async genTitle() {
if (!this._title) {
if (!this._genTitlePromise) {
this._genTitlePromise = this._genTitle();
}
await this._genTitlePromise;
}
return this._title;
}
}
您只需要稍后開始等待,因此this._title將是promise的一個實例。 我在現實生活中會以不同的方式命名(this._title):
class ArticleParser {
async genTitle() {
if (!this._title) {
this._title = takesALongTime();
}
return await this._title;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.