一、Promise是個(gè)啥?
Promise是JavaScript中用于處理異步操作的對象,代表一個(gè)異步操作的最終完成(或失敗)及其結(jié)果值。它有三種狀態(tài): pending (進(jìn)行中)、 fulfilled (已成功)和 rejected (已失敗)。狀態(tài)一旦改變,就不會再變。
二、手寫Promise基本結(jié)構(gòu)
function MyPromise(executor) {
// 初始狀態(tài)為pending
this.state = 'pending';
// 成功的值
this.value = undefined;
// 失敗的原因
this.reason = undefined;
// 存儲成功回調(diào)函數(shù)
const resolveCallbacks = [];
// 存儲失敗回調(diào)函數(shù)
const rejectCallbacks = [];
// 定義resolve函數(shù)
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
// 依次執(zhí)行成功回調(diào)
resolveCallbacks.forEach(callback => callback());
}
};
// 定義reject函數(shù)
const reject = (reason) => {
if (this.state === 'pending') {
this.state ='rejected';
this.reason = reason;
// 依次執(zhí)行失敗回調(diào)
rejectCallbacks.forEach(callback => callback());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
三、實(shí)現(xiàn)then方法
then 方法用于為Promise添加成功和失敗回調(diào)。
MyPromise.prototype.then = function (onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function'? onFulfilled : value => value;
onRejected = typeof onRejected === 'function'? onRejected : reason => { throw reason };
return new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
}
if (this.state ==='rejected') {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
}
if (this.state === 'pending') {
this.resolveCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
});
this.rejectCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
});
}
});
};
四、輔助函數(shù)resolvePromise
處理 then 回調(diào)返回值的邏輯。
function resolvePromise(resolve, reject, x) {
if (x === resolvePromise) {
return reject(new TypeError('Chaining cycle detected for promise'));
}
let called = false;
if (x!== null && (typeof x === 'object' || typeof x === 'function')) {
try {
const then = x.then;
if (typeof then === 'function') {
then.call(x, y => {
if (called) return;
called = true;
resolvePromise(resolve, reject, y);
}, r => {
if (called) return;
called = true;
reject(r);
});
} else {
resolve(x);
}
} catch (error) {
if (called) return;
called = true;
reject(error);
}
} else {
resolve(x);
}
}
五、測試MyPromise
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
promise.then(value => {
console.log(value);
return 'New value';
}).then(newValue => {
console.log(newValue);
});
OK 到這里一個(gè)簡單的手寫Promise就實(shí)現(xiàn)了,涵蓋了Promise的基本狀態(tài)管理、 then 方法及處理回調(diào)返回值的邏輯。
該文章在 2024/12/25 10:19:24 編輯過