手写promise
//excutor 为promise回调函数
function myPro(excutor) {
this.state = 'pending'; //状态
this.value = undefined; //回调成功值
this.reason = undefined; //回调失败原因
this.onFulfilleds = []; //成功回调函数组
this.onRejecteds = []; //失败回调函数组
resolve = value => {
//判断改变状态
if(this.state == 'pending'){
this.value = value; //记录回调成功值
this.state = 'resolved'; //更改状态
//触发成功回调函数,并传递回调成功值
this.onFulfilleds.forEach(fn=>{
this.value = fn(this.value);
});
}
}
reject = reason => {
//判断改变状态
if(this.state == 'pending'){
this.reason = reason; //记录失败回调值
this.state = 'rejected'; //更改状态
//触发失败回调函数,并传递回调失败值
this.onRejecteds.forEach(fn=>{
this.reason = fn(this.reason);
});
}
}
//执行promise回调函数,传递resolve函数,reject函数
excutor(resolve,reject);
};
//在原型上添加then方法
myPro.prototype.then = function (onFulfilled,onRejected){
//类型判断,并加入成功回调函数组
if(typeof onFulfilled === 'function'){
this.onFulfilleds.push(onFulfilled);
}
//类型判断,并加入失败回调函数组
if(typeof onRejected === 'function'){
this.onRejecteds.push(onRejected);
}
//返回当前实例
return this;
};
//创建mypro实例
let p = new myPro((resolve,reject)=>{
console.log('promise 执行');
setTimeout(()=>{
resolve(1);
//reject('出错');
},500);
});
p.then(res=>{
console.log('成功回调:'+res);
return res+1;
},err=>{
console.log('失败回调:'+err);
return err+':出错';
}).then(res=>{
console.log('成功回调:'+res);
});
输出:
promise 执行
成功回调:1
成功回调:2