记一次失败的StackOverflow回答
2024-10-21 03:18:58
有一位同学在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));
运行结果为
可以说是非常完美的实现了需求,但是为什么说是一次失败的尝试呢?
因为题主把问题删了!!
可能是因为被人点了踩,或者是自己意识到这是反模式吧,总之我在解决这个问题的过程中获得了成长(this指向,bind函数细节,super用法,复习异步代码,混入mixin,私有字段)
今天就到这里吧,撒由那拉~~
最新文章
- J2EE项目修改编码问题
- map 取值
- CentOS6.5源码安装python3.5.2
- 《The Linux Command Line》 读书笔记03 ls命令与长格式输出解释 文件权限
- Xcode 7中http通信出现如下错误:Application Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
- html5的一些表单属性。
- 【经典算法】——KMP,深入讲解next数组的求解
- Cento OS 6.5 YUM 安装 R 的方法
- android 学习随笔十九(对话框、样式、主题、国际化 )
- matlab 2012 vs2010混合编程
- 15个必须知道的chrome开发者技巧
- 百度编辑器解决span被过滤, 自动加P标签
- js pix
- 360手机助手内部资料曝光,63张PPT纯干货
- java 集合接口及类
- 微软提供的API的各个版本之间的区别
- Change value of string array at debug eclipse--转
- 外国的Delphi网站
- 第1章1zabbix快速入门
- 再起航,我的学习笔记之JavaScript设计模式02
热门文章
- 2022春每日一题:Day 34
- java 分布式游戏服务器框架,集群游戏服务器框架,游戏服务器网关框架 ioGame 网络游戏服务器框架
- 使用c#的 async/await编写 长时间运行的基于代码的工作流的 持久任务框架
- 关于Module Not Found Error No module named Crypto解决
- jquery &;&;、||
- VBA驱动SAP GUI自动化:查找页面元素FindAllByName
- ARC145~152 题解
- RGB以及RGBA
- 如何搭建自己的CICD流水线,实现自动编译部署功能?
- 从零入门项目集成Karate和Jacoco,配置测试代码覆盖率