let PENDING = "PENDING";
let FULFILLED = "FULFILLED";
let REJECTED = "REJECTED";
class MyPromise{
constructor(callback){
//判断传入promise的参数是不是函数类型
if(typeof callback !== "function"){
console.error("argument is not a function!")
return new Error("argument is not a function!")
}
//初始化promise的状态
this.status = PENDING;
//定义返回值
this.res;
//then回调函数的队列
this._fulfilledQueues = [];
this._rejectedQueues = [];
callback(this._resolve.bind(this), this._reject.bind(this))
}
//定义传入callback函数的resolve函数(更合理的应该是_resolve和_reject方法定义在constructor里,因为promise实例没有这两个方法)
_resolve(param){
//加上状态的判断是因为promise的状态一旦更改,就不会改变这个特性,为了避免用户多次调用resolve/reject函数造成的状态更改
if(this.status !== PENDING){
return;
}
//更改promise实例的状态为成功resolve
this.status = FULFILLED;
this.res = param;
//状态改变,调用队列中的函数
this._fulfilledQueues.forEach((fn, index) => {
fn(this.res)
})
}
_reject(err){
//加上状态的判断是因为promise的状态一旦更改,就不会改变这个特性,为了避免用户多次调用resolve/reject函数造成的状态更改
if(this.status !== PENDING){
return;
}
this.status = REJECTED;
this.res = new Error(err)
//状态改变,调用then中的函数
this._rejectedQueues.forEach((fn, index) => {
fn(this.res)
})
}
//then方法
then(onFulfilled, onRejected){
//从实例中取出promise对象的当前状态
const {status, res} = this;
switch(status) {
case PENDING : //将then方法的函数加入队列(状态还处在pending状态,只有在状态改变后,才会从队列中取出函数进行调用,现在先进行存储)
this._fulfilledQueues.push(onFulfilled)
this._rejectedQueues.push(onRejected)
break;
case FULFILLED ://执行当前then传入的成功回调函数(因为状态已经确定,所以立马执行函数)
onFulfilled(res)
break;
case REJECTED : //执行当前then传入的失败回调函数(因为状态已经确定,所以立马执行函数)
onRejected(res)
break;
}
//返回新promise对象,以便可以链式调用then方法
//注意,不太懂onFulfilledNext, onRejectedNext
return new MyPromise((onFulfilledNext, onRejectedNext)=>{})
}
}
网友评论