上一篇文章實(shí)現(xiàn)了Promise最基礎(chǔ)功能辽社,本文將實(shí)現(xiàn)promise核心的鏈?zhǔn)秸{(diào)用
const PENDING_STATUS = 'pending';
const FULFILLED_STATUS = 'fulfilled';
class MyPromise {
callBacks = [];// {onFulfilled, resolve}組合push到這個(gè)數(shù)組中
state = PENDING_STATUS;// state初始狀態(tài)
value = null;// 保存resolve傳遞過(guò)來(lái)的參數(shù)
constructor(fn) {
fn(this.resolve)
}
then = (onFullfilled) => {
return new MyPromise((resolve) => {
this.handle({
onFullfilled,
resolve
});
});
}
handle = (cb) => {
if(this.state === PENDING_STATUS) { // 異步的話就先存著刺彩,后面再執(zhí)行
this.callBacks.push(cb);
return;
}
if (!cb.onFullfilled) {// onFullfilled如果是空渤昌,就把結(jié)果直接傳給下一個(gè)then
cb.resolve(this.value);
return;
}
var ret = cb.onFullfilled(this.value);
cb.resolve(ret);// 鏈?zhǔn)秸{(diào)用的關(guān)鍵,把返回結(jié)果傳遞給下一個(gè)resolve
}
resolve = (value) => {
// resolve傳過(guò)來(lái)的,除了數(shù)值,還有可能是上一個(gè)then返回的promise驹愚,下面這個(gè)if主要處理這種情況
if (value && (typeof value === 'object' || typeof value === 'function')) {
var then = value.then;
if (typeof then === 'function') {
then.call(value, this.resolve); // 如果是一個(gè)promise,則調(diào)用它的then
return;
}
}
this.state = FULFILLED_STATUS;
this.value = value;
this.callBacks.forEach(cb => {
this.handle(cb);
});
}
}
// 鏈?zhǔn)秸{(diào)用的使用舉例
const promise = new MyPromise((resolve) => {
setTimeout(() => {
resolve('第一個(gè)結(jié)果');
},3000);
})
.then((result) => {
return new MyPromise((resolve) => {
setTimeout(() => {
resolve(result + ' 第二個(gè)結(jié)果');
}, 3000);
});
})
.then((result) => {
return new MyPromise((resolve) => {
setTimeout(() => {
resolve(result + ' 第三個(gè)結(jié)果');
}, 3000);
});
}).then((result) => {
console.log(result);
});```