用 class 手写一个 Promise

class Promise {
constructor(executer) { //构造函数 constructor 里面是个执行器
this.status = 'pending'; //默认的状态 pending
this.value = undefined //成功的值默认 undefined
this.reason = undefined //失败的值默认 undefined
//状态只有在 pending 时候才能改变
let resolveFn = value=>{
//判断只有等待时才能 resolve 成功
if (this.status == 'pending') {
this.status = 'resolve';
this.value = value;
}
}
//判断只有等待时才能 reject 失败
let rejectFn = reason=>{
if (this.status == 'pending') {
this.status = 'reject';
this.reason = reason;
}
}
try {
//把 resolve 和 reject 两个函数传给执行器 executer
executer(resolveFn, rejectFn);
} catch(e) {
rejectFn(e); //失败的话进 catch
}
}
then(onFufilled, onReject) {
//如果状态成功调用 onFufilled
if (this.status == 'resolve') {
onFufilled(this.value);
}
//如果状态失败调用 onReject
if (this.status == 'reject') {
onReject(this.reason);
}
}
}

 

var P = new Promise((resolve, reject) => { //初始化参数
resolve('success1')//调用并传参
reject('error')
})
P
.then((res) => {
console.log('then: ', res)//被回调
},(res) => {
console.log('then: ', res)
})

posted @ 2021-10-17 12:39  果果1024  阅读(156)  评论(0)    收藏  举报