// 表示狀態(tài),便于后期維護
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
function MyPromise(fn) {
// 因代碼可能會異步執(zhí)行,用于獲取正確的this對象
const that = this;
// 初始狀態(tài)為pending
that.state = PENDING;
// 用于保存resolve 或者 reject 中傳入的值
that.value = null;
// 用于保存then中的回調(diào),因為當(dāng)執(zhí)行完P(guān)romise時狀態(tài)可能還是等待中砚殿,
// 這時候應(yīng)該把then中的回調(diào)保存起來用戶狀態(tài)改變時使用
that.resolvedCallbacks = [];
that.rejectedCallbacks = [];
// 首先兩個函數(shù)都得判斷當(dāng)前狀態(tài)是否是等待中轰枝,因為只有等待狀態(tài)可以改變狀態(tài)
// 將當(dāng)前狀態(tài)更改為對應(yīng)狀態(tài)凳忙,并且將傳入的值賦值給value
// 遍歷回調(diào)數(shù)組并執(zhí)行
function resolve(value) {
if(that.state === PENDING) {
that.state = RESOLVED;
that.value = value;
that.resolvedCallbacks.map(cb => cb(that.value));
}
}
function reject(value) {
if(that.state === PENDING) {
that.state = REJECTED;
that.value = value;
that.rejectedCallbacks.map(cb => cb(that.value));
}
}
// 執(zhí)行傳入的參數(shù)并且將之前的兩個函數(shù)當(dāng)做參數(shù)傳進去
// 注意: 可能執(zhí)行函數(shù)過程中會遇到錯誤移稳,需要捕獲錯誤并執(zhí)行reject函數(shù)
try{
fn(resolve, reject)
} catch (e) {
reject(e);
}
}
MyPromise.prototype.then = function(onFulfilled, onRejected) {
const that = this;
// 首先判斷兩個參數(shù)是否為函數(shù)類型走诞,因為這兩個參數(shù)時可選參數(shù)
// 當(dāng)參數(shù)不是函數(shù)類型時摔笤,需要創(chuàng)建一個函數(shù)賦值給對應(yīng)的參數(shù)够滑,同時也實現(xiàn)了透傳
// eg: Promise.resolve(4).then().then(value => console.log(value))
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r; };
// 判斷狀態(tài)
// 當(dāng)狀態(tài)不是等待態(tài)時,就去執(zhí)行相應(yīng)的函數(shù)吕世。
// 如果狀態(tài)是等待態(tài)的話彰触,就往回調(diào)函數(shù)中push函數(shù)
if(that.state === PENDING) {
that.resolvedCallbacks.push(onFulfilled);
that.rejectedCallbacks.push(onRejected);
}
if(that.state === RESOLVED) {
onFulfilled(that.value);
}
if(that.state === REJECTED) {
onRejected(that.value)
}
};
eg:
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 0)
}).then(value => {
console.log(value)
});