记一次失败的***回答

科技资讯 投稿 6700 0 评论

记一次失败的***回答

Future 类,异步的实现 Future 的构造,当构造完成之后自动调用 .then 方法,执行后面的逻辑

class Features {
  features = null
  constructor({
    fetchFeatures(
  }
  async fetchFeatures( {
    this.features = await fetch('https://api.github.com/'
  }
}

const featuresInstance = new Features(;
featuresInstance.then((res => console.log(featuresInstance.features;

我第一眼想到的是继承 Promise 但是继承 Promise 是行不通的,具体请看 这里
简单来说就是 Promise 的运行需要运行时提供魔法,不能简单的通过 super 构造函数传参来执行,另外即便可以传参,也无法使用this,起不到题主要求的封装的效果

下面给出题主要求的伪需求的实现方式

class Features {
  features = null
  #prom = null
  constructor({
    return Object.assign(this,this.#prom = new Promise(this.fetchFeatures.bind(this
  }
  then(callback {
    return this.#prom.then(callback
  }
  async fetchFeatures(resolve {
    resolve(this.features = await fetch('https://api.github.com/'
  }
}

const featuresInstance = new Features(;
featuresInstance.then((res => console.log(featuresInstance;

运行结果为
可以说是非常完美的实现了需求,但是为什么说是一次失败的尝试呢?


今天就到这里吧,撒由那拉~~

编程笔记 » 记一次失败的***回答

赞同 (33) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽