沒做catch,如果理解了下面代碼,catch不難實現。
const RESOLVED = "resolved";
const PENDING = "pending";
function MyPromise(fn) {
this.status = PENDING;
this.value = null;
this.resolveCBs = [];
// promise創建的時候的resolve函數
const _resolve = (value) => {
const that = this;
// 如果resolve傳入的value是個promise,那么就把當前的resolve傳給value.then
// 等待value這個promise解決之后再執行當前resolve函數
if (value instanceof MyPromise) {
return value.then(_resolve);
}
this.status = RESOLVED;
this.value = value;
// 當前promise完成,把掛在上面的callback全部執行一遍
this.resolveCBs.forEach((resolveCB) => {
resolveCB(that.value);
});
};
fn(_resolve);
}
// then函數要返回promise
MyPromise.prototype.then = function (onfulfilled) {
const that = this;
// 如果當前promise還沒解決,創建一個新的promise,
// 把新promise的resolve塞入resolveCBs數組
// 同時把這個promise返回出去
if (that.status === PENDING) {
return new MyPromise((resolve) => {
that.resolveCBs.push((val) => {
resolve(onfulfilled(val));
});
});
} else if (that.status === RESOLVED) {
// 當前promise已經解決,直接將值傳過去
let result = onfulfilled(that.value);
if (result instanceof MyPromise) {
return result;
} else {
return new MyPromise((resolve) => {
resolve(that.value);
});
}
}
};
let p = new MyPromise((resolve) => {
setTimeout(() => {
console.log(100);
resolve(100);
}, 1000);
})
.then(
(value) =>
new MyPromise((resolve) => {
setTimeout(() => {
console.log(value + 1);
resolve(value + 1);
}, 1000);
})
)
.then((value) => console.log(value + 1));
// 預期結果
// 0ms:
// 1000ms: 100
// 2000ms: 101 102