手写promise核心代码(一)

发布时间 2023-09-21 15:47:01作者: 努力不搬砖的iori

 

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
}
}
}

 

到目前位置,就实现了 状态改变这一部分