手写promise核心代码(一)
class myPromise {
static PENDING = 'pending'
static REJECT = 'reject'
static RESOLVE = 'resolve';
constructor(executor) {
this.value = null
this.status = myPromise.PENDING
try {
executor(this.resolve1.bind(this), this.reject.bind(this))
} catch (error) {
// 代码执行出错也reject
this.reject(error)
}
// 目前到这里就会有this 指向的问题, 因为到类实例化调用的时候,都是在window下,
//或者在某一个函数内,此时this 指向window ,严格模式下,class 类都是undefined
// 所以这里需要手动绑定this
}
resolve1(value) {
// mmp 原来 class 里面 resolve 已经是个关键字了, 怎么说开始都不起resolve作用
if (this.status == 'pending') { //promise 状态只允许改变一次,所以不是pending 状态都不给改
this.value = value
this.status = myPromise.RESOLVE
}
}
reject(reason) {
if (this.status == 'pending') {
this.value = reason
this.status = myPromise.REJECT
}
}
}
到目前位置,就实现了 状态改变这一部分
本文作者:CV攻城狮中的一员
本文链接:https://www.cnblogs.com/Hijacku/p/17720111.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步