function MyPromise(executor) {
// 初始状态为 Pending
this.status = 'pending';
// 用于保存 resolve 和 reject 的值
this.value = undefined;
this.reason = undefined;
// 用于存储成功和失败的回调函数
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
// 定义 resolve 函数
const resolve = (value) => {
// 只有在状态为 Pending 时才能执行 resolve
if (this.status === 'pending') {
// 将状态改为 Resolved
this.status = 'resolved';
// 保存 resolve 的值
this.value = value;
// 执行成功的回调函数
this.onResolvedCallbacks.forEach(callback => callback());
}
};
// 定义 reject 函数
const reject = (reason) => {
// 只有在状态为 Pending 时才能执行 reject
if (this.status === 'pending') {
// 将状态改为 Rejected
this.status = 'rejected';
// 保存 reject 的原因
this.reason = reason;
// 执行失败的回调函数
this.onRejectedCallbacks.forEach(callback => callback());
}
};
// 执行传入的 executor 函数,并传入 resolve 和 reject 函数
try {
executor(resolve, reject);
} catch (error) {
// 如果执行过程中发生异常,将其作为 reject 的原因处理
reject(error);
}
}
// 添加 then 方法
MyPromise.prototype.then = function(onFulfilled, onRejected) {
if (this.status === 'resolved') {
// 如果状态为 Resolved,执行成功回调函数
onFulfilled(this.value);
} else if (this.status === 'rejected') {
// 如果状态为 Rejected,执行失败回调函数
onRejected(this.reason);
} else if (this.status === 'pending') {
// 如果状态为 Pending,将成功和失败的回调函数保存起来
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value);
});
this.onRejectedCallbacks.push(() => {
onRejected(this.reason);
});
}
};
// 示例用法
const myPromise = new MyPromise((resolve, reject) => {
// 异步操作,比如 setTimeout
setTimeout(() => {
// 模拟异步操作成功,调用 resolve
resolve('成功的结果');
}, 1000);
});
// 使用 then 方法处理成功和失败的情况
myPromise.then(
result => {
console.log('成功:', result);
},
reason => {
console.log('失败:', reason);
}
);
【JS】手写promise方法
最新推荐文章于 2024-04-04 15:48:33 发布