繁体   English   中英

在JavaScript中共享异步函数响应的干净方法是什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM