static PENDING = "pending";//准备状态
static FULFILLED = "fulfilled";//解决状态
static REJECTED = "rejected";//拒绝状态
|
1.初始化状态、值、then中没 有处理的函数数组
2.将resolve和reject函数传递 出去
constructor(executor) {
this.status = MyPromise.PENDING;//初始化状态
this.value = null;//初始化值
this.callbacks = [];//待处理的函数
try {
// 在执行(resolve,reject)=> {} 如果发送报错,则把状态改为拒绝状态,并且把结果返回出去
// 参数这边为是实参 函数执行体为那边
executor(this.resolve.bind(this), this.reject.bind(this));//执行构造时传入的回调函数
} catch (error) {
this.reject(error)
}
}
|
1.判断是否为准备状态
2.是—>改变状态和值、以及异步轮询 then 中没有执行完成的函数
resolve函数 reject函数类似 |
//发起解决
resolve(value) {
//先判断状态 为避免执行完resolve 后又执行reject导致重复改变状态
if (this.status == MyPromise.PENDING) {
this.status = MyPromise.FULFILLED;//改变状态
this.value = value;//改变值
//resolve和reject执行被放到setTimeout中,执行在then还没有执行的函数
/*将then中没有执行的代码放到setTimeout中异步执行为了避免与resolve有同级的同步代码
例如
setTimeout(() => {
resolve("后盾人");
console.log("大叔视频");
});*/
setTimeout(() => {
this.callbacks.map(callback => {
callback.onFulfilled(this.value);
})
}, 0)
}
}
|
then函数 |
1. 判断onFuilled/onRejected是否为函数 |
//执行重置函数将this.value传入并返回给下一个promise对象
if (typeof onFulfilled != "function") {
onFulfilled = value => value;
}
if (typeof onRejected != "function") {
onRejected = value => value;
}
|
2. 返回一个新MyPromise |
该MyPromise的创建需要拿上一个MyPromise在onFuilled/onRejected完处理的数据进行初始化 |
- 没有处理的状态
if (this.status == MyPromise.PENDING) {
this.callbacks.push({
onFulfilled: value => {
this.parse(mypromise, onFulfilled(value), resolve, reject);
},
onRejected: value => {
this.parse(mypromise, onRejected(value), resolve, reject);
}
})
}
|
- 成功状态
if (this.status == MyPromise.FULFILLED) {
setTimeout(() => {
this.parse(mypromise, onFulfilled(this.value), resolve, reject);
})
}
|
- 拒绝状态
if (this.status == MyPromise.REJECTED) {
setTimeout(() => {
this.parse(mypromise, onRejected(this.value), resolve, reject);
})
}
|
parse函数
parse(mypromise, result, resolve, reject) {
//不能返回相同的mypromise
if (mypromise == result) {
throw new TypeError("Chaining cycle detected");
}
try {
//如果是返回值是一个MyPromise对象,需要执行多一次then
if (result instanceof MyPromise) {
result.then(
value => {
//初始化新创建的MyPromise
resolve(value);
},
reason => {
//初始化新创建的MyPromise
reject(reason);
}
)
} else {
//新创建的myPromise对象默认执行resolve方法
resolve(result);
}
} catch (error) {
reject(error)
}
}
|
|
|