class Mypromise {
constructor(cb) {
this.status = 'pending';
this.data = null;
this.resolveArr = [];
this.rejecteArr = [];
this.resolve = val => {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.data = val
this.resolveArr.forEach(cbs=> {
cbs();
})
}
}
this.reject = err => {
if (this.status === 'pending') {
this.status = 'rejected';
this.data = err
this.rejecteArr.forEach(cbs => {
cbs();
})
}
}
cb(this.resolve, this.reject);
}
then(success, fail) {
success = typeof success === 'function' ? success : function (val) { return val };
fail = typeof fail === 'function' ? fail : function (val) { return val };
// 得考虑三种状态
// 等待的状态
if (this.status === 'pending') {
// 成功集合
this.resolveArr.push(() => {
success(this.data);
});
// 失败的集合
this.rejecteArr.push(() => {
fail(this.data);
});
}
// 成功的状态
if (this.status === 'fulfilled') {
success(this.data);
}
// 失败的状态
if (this.status === 'rejected') {
fail(this.data);
}
}
catch(fail){
this.then(null, fail);
}
}
// 自己的
let mpro = new Mypromise(function (resolve, reject) {
// 同步
// resolve(1);
// reject(0);
// 异步
setTimeout(() => {
resolve(22222);
// reject(-1);
},1000);
});
mpro.then((data) => {
console.log(data, '成功了');
}, (err) => {
console.log(err, '失败了');
});
mpro.catch((err) => {
console.log(err, 'err');
});
网友评论