通过实现Promise,更好地理解Promise,欢迎有问题的同学评论
class MyPromise {
callBacks = [];// then的回调push到这个数组中
state = 'pending';// state初始状态
value = null;// 保存resolve传递过来的参数
constructor(fn) {
fn(this.resolve)
}
then = (onFullfilled, onRejected) => {
if (this.state === 'pending') { // 执行then时候状态还是pending,说明是异步的
this.callBacks.push(onFullfilled);
return;
} else {
onFullfilled(this.value);
}
}
resolve = (value) => {
this.state = 'fulfilled'
this.value = value;
this.callBacks.forEach(cb => {
cb(value);
});
}
}
// 使用
const promise = new MyPromise((resolve, reject) => {
resolve('操作成功!');
});
promise.then(res => {
console.log('成功结果:' + res);
});
下一篇文章我将实现Promise比较关键的链式调用