简体   繁体   中英

What's a clean way to share async function response in Javascript?

I have async functions similar to this:

class ArticleParser() {
  _title;

  async genTitle() {
    if (!this._title) {
      this._title = await takesALongTime();
    }

    return this._title;
  }
}

If genTitle is called multiple times before the first call finishes, it will call takesALongTime multiple times. I want all calls to genTitle to share the same returned promise. Is there a clean/simple way to do so?

Here's a solution that works, but it looks pretty messy:

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;
  }
}

You just need to start waiting later so this._title will be an instance of promise. I would name it (this._title) differently in real life:

class ArticleParser {
  async genTitle() {
    if (!this._title) {
      this._title = takesALongTime();
    }

    return await this._title;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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