自己的Promise
自己 Promise
2023-09-14 08:58:55 时间
废话不多说,直接上代码:
class myPromise { constructor(fn) { this.status = 'pending'; this.resolveCbs = []; this.rejectCbs = []; this.value = null; fn(this._resolve.bind(this), this._reject.bind(this)); return this; } _resolve(val) { if (this.status === 'pending') { this.value = val; this.status = 'fulfilled'; this.resolveCbs.forEach(cb => { cb(this.value); }) } } _reject(err) { if (this.status === 'pending') { this.value = err; this.status = 'rejected'; this.rejectCbs.forEach(cb => { cb(this.value); }) // 如果没有处理函数,则直接抛错 if (this.rejectCbs.length === 0) { throw err } } } then(resolveCb, rejectCb) { if (this.status !== 'pending') { const cb = this.status === 'fulfilled' ? resolveCb : rejectCb; const self = new myPromise((resolve, reject) => { this._handleCb(cb, this.value, resolve, reject, self); }) return self; } else { const self = new myPromise((resolve, reject) => { if (typeof resolveCb === 'function') { this.resolveCbs.push(res => { this._handleCb(resolveCb, res, resolve, reject, self); }) } if (typeof rejectCb === 'function') { this.rejectCbs.push(res => { this._handleCb(rejectCb, res, resolve, reject, self); }) } }) return self; } } catch(rejectCb) { return this.then(null, rejectCb) } _handleCb(cb, res, resolve, reject, self) { try { const ret = cb(res) if (ret instanceof Promise || ret instanceof myPromise) { if (ret === self) { throw new Error('检测到myPromise链式循环') } ret.then(res => resolve(res)) } else { resolve(ret) } } catch (err) { reject(err) } } } new myPromise((resolve, reject) => { setTimeout(() => { resolve(456) }, 1000); }).then(res => { console.log(res) throw 'hualala' }).catch(err => { console.log('heng!!!') return new myPromise((resolve, reject) => { setTimeout(() => { reject(233) }, 1000); }) }).then(res => { console.log(res) })
这个简版的Promise已经可以实现到链式的地步了, 如果return是一个非Promise,则直接resolve,如果是Promise,则等then再resolve
相关文章
- 人生九段算法:用算法经营自己的人生(5-9段)
- 【全流程】从头在树莓派4B上部署自己训练的yolov5模型(配合NCS2加速)
- 使用云服务器与calibre-web构建自己的在线书架(2022年版)
- ChatGPT对自己的调研
- 马斯克称自己有可能被暗杀/ B站回应新一轮裁员/ 推特拒绝做开源开发…今日更多新鲜事在此
- 使用 YOURLS 创建自己的 URL 缩短服务
- 该程序在运行时会创建一个JOB,并且将该自己以JOB后台方式运行,并且可以从前台传递参数到后台JOB详解编程语言
- 教你一招即使没有服务器,也可以免费拥有自己的专属网站(静态网站)
- 视频会议时,我们为何总会盯着自己的脸?
- nagios中自己写的监控mysql主从复制的插件
- 如何搭建家庭Linux服务器?25步骤,让你一次拥有自己的高效服务器。(家庭linux服务器搭建)
- 构建自己的域:Oracle为你开路(oracle 创建域)
- 拒绝大疆后,GoPro终于为自己当年的任性买单了
- 开发者可以基于Achain发布自己的区块链,搭建平行网络“星系”
- 用Composer构建自己的PHP框架之构建路由