class MyPromise {
constructor(fn) {
this.state = "open";
this.result = null;
this.callBack = [];
// 绑定this,并接受参数 => bind
fn(MyPromise.resolve.bind(this), MyPromise.reject.bind(this));
}
// 静态方法
static resolve(params) {
this.state = "success";
this.result = params;
this.callBack.forEach(item => {
const { resFn, resolve } = item.success;
resolve(resFn(this.result))
});
}
// 静态方法
static reject(params) {
this.state = "full";
this.result = params;
this.callBack.forEach(item => {
const { rejFn, reject } = item.full;
reject(rejFn(this.result))
});
}
then(resFn, rejFn) {
const _this = this;
// 返回的是promise, 同时将then返回值,作为下个then函数的接收值
return new MyPromise(function (resolve, reject) {
if (_this.state === 'open') {
_this.callBack.push({
success: {
resFn,
resolve
},
full: {
rejFn,
reject
}
});
} else if (_this.state === 'success') {
var d = resFn(_this.result);
resolve(d);
} else if (_this.state === 'full') {
var d = rejFn(_this.result);
reject(d);
}
});
// if (this.state === 'open') {
// // new MyPromise内部异步操作,then函数先执行了
// // 这时候由于resolve, reject函数并未执行,resolve, reject函数执行的结果,并未绑定在this.result上
// // resFn, rejFn函数执行,时获取不到this.result上的结果
// this.callBack.push({
// success: resFn,
// full: rejFn
// });
// } else if (this.state === 'success') {
// // new MyPromise内部同步操作,then函数先执行了
// resFn(this.result);
// } else if (this.state === 'full') {
// // new MyPromise内部同步操作,then函数先执行了
// rejFn(this.result);
// }
}
};
const myP = new MyPromise(function (resolve, reject) {
setTimeout(function () {
resolve(26)
}, 1000);
});
myP.then(function (res) {
console.log(res);
return 23;
}).then(function (res) {
console.log(res, '888');
})
手写一个Promise
最新推荐文章于 2024-04-21 17:56:07 发布