上一篇文章实现了Promise最基础功能,本文将实现promise核心的链式调用
const PENDING_STATUS = 'pending';
const FULFILLED_STATUS = 'fulfilled';
class MyPromise {
callBacks = [];// {onFulfilled, resolve}组合push到这个数组中
state = PENDING_STATUS;// state初始状态
value = null;// 保存resolve传递过来的参数
constructor(fn) {
fn(this.resolve)
}
then = (onFullfilled) => {
return new MyPromise((resolve) => {
this.handle({
onFullfilled,
resolve
});
});
}
handle = (cb) => {
if(this.state === PENDING_STATUS) { // 异步的话就先存着,后面再执行
this.callBacks.push(cb);
return;
}
if (!cb.onFullfilled) {// onFullfilled如果是空,就把结果直接传给下一个then
cb.resolve(this.value);
return;
}
var ret = cb.onFullfilled(this.value);
cb.resolve(ret);// 链式调用的关键,把返回结果传递给下一个resolve
}
resolve = (value) => {
// resolve传过来的,除了数值,还有可能是上一个then返回的promise,下面这个if主要处理这种情况
if (value && (typeof value === 'object' || typeof value === 'function')) {
var then = value.then;
if (typeof then === 'function') {
then.call(value, this.resolve); // 如果是一个promise,则调用它的then
return;
}
}
this.state = FULFILLED_STATUS;
this.value = value;
this.callBacks.forEach(cb => {
this.handle(cb);
});
}
}
// 链式调用的使用举例
const promise = new MyPromise((resolve) => {
setTimeout(() => {
resolve('第一个结果');
},3000);
})
.then((result) => {
return new MyPromise((resolve) => {
setTimeout(() => {
resolve(result + ' 第二个结果');
}, 3000);
});
})
.then((result) => {
return new MyPromise((resolve) => {
setTimeout(() => {
resolve(result + ' 第三个结果');
}, 3000);
});
}).then((result) => {
console.log(result);
});```