s

手写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 中国大陆许可协议进行许可。

posted @   努力不搬砖的iori  阅读(4)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.