• 记一次失败的StackOverflow回答


    有一位同学在StackOverflow上提问,他想创建一个 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,起不到题主要求的封装的效果

    首先说明题主的需求是一个伪需求,异步加载资源可以通过Promise来实现,没必要封装到构造函数里

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

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

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


    因为题主把问题删了!!😢😢😢

    image

    可能是因为被人点了踩,或者是自己意识到这是反模式吧,总之我在解决这个问题的过程中获得了成长(this指向,bind函数细节,super用法,复习异步代码,混入mixin,私有字段)

    (注意mixin是向prototype中assign目标对象,我这里并不是正规mixin)

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

  • 相关阅读:
    LeetCode刷题笔记-749. 隔离病毒-模拟+搜索
    【C++】二叉堆和优先队列
    LVS负载均衡集群
    「杰伦熊」暴跌96.6% 明星带货NFT为何遇冷?
    Node.js【模块化的基本概念、Node.js 中的模块化、npm与包】
    哈希及其应用
    Linux安装RabbitMQ
    确保使用正确的CSI提交HW问题
    关于electron打包卡在winCodeSign下载问题
    二十三种设计模式全面解析-深入解析模板方法模式的奇妙世界
  • 原文地址:https://www.cnblogs.com/dou-fu-gan/p/17112393.html