javascript 双重承诺实施

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 双重承诺实施相关的知识,希望对你有一定的参考价值。

class CachedDataFetcher {
  static create(...args) {
    return new CachedDataFetcher(...args)
  };

  constructor({
    url,
  }) {
    this
    .url = url

    this
    .dataHandlers = []

    this
    .activateDataHandlers = (
      this
      .activateDataHandlers
      .bind(this)
    )

    this
    .fetchData = (
      this
      .fetchData
      .bind(this)
    )

    this
    .storeResponseInCache = (
      this
      .storeResponseInCache
      .bind(this)
    )
  }

  activateDataHandlers(data) {
    if (data === this.cachedData) {
      return null
    }

    this
    .cachedData = data

    this
    .dataHandlers
    .reduce(
      (
        returnValue,
        dataHandler,
      ) => (
        dataHandler(
          data
        )
      ),
      data,
    )

    return data
  }

  done() {
    this
    .fetchCache()
  }

  fetchCache() {
    return (
      caches
      .match(this.url)
      .then(response => (
        response
        && (
          response
          .text()
        )
      ))
      .then(this.activateDataHandlers)
      .then(this.fetchData)
    )
  }

  fetchData() {
    return (
      fetch(this.url)
      .then(this.storeResponseInCache)
      .then(response => (
        response
        .clone()
        .text()
      ))
      .then(this.activateDataHandlers)
    )
  }

  storeResponseInCache(response) {
    caches
    .open('v1')
    .then(cache => (
      cache
      .put(
        this.url,
        response,
      )
    ))

    return response
  }

  then(dataHandler) {
    this
    .dataHandlers
    .push(dataHandler)

    return this
  }
}

以上是关于javascript 双重承诺实施的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 双重链表OO实施

防止在后端ASP.NET Core 3中提交双重形式的提交。*

javascript 承诺所有运行所有承诺和处理程序错误

案例方式学习JavaScript双重for循环

类函数中的 Javascript ES6 承诺

JavaScript承诺 - 多个承诺失败时的逻辑