当我们谈到 JavaScript 异步编程时,Promise 是一个非常重要的概念。Promise 是一种用于处理异步操作的对象,它代表了一个异步操作的最终完成或失败,并可以获取其结果。在本文中,我将手写一个简单的 Promise 实现,以帮助你更好地理解 Promise 的工作原理。
首先,让我们定义一个 Promise 的基本结构:
class MyPromise {
constructor(executor) {
// 初始化状态为等待中
this.status = 'pending';
// 用于保存成功时的数据
this.value = undefined;
// 用于保存失败时的原因
this.reason = undefined;
// 用于存储成功回调函数
this.onResolvedCallbacks = [];
// 用于存储失败回调函数
this.onRejectedCallbacks = [];
// 定义 resolve 函数,用于将 Promise 状态变更为成功
const resolve = (value) => {
// 只有在状态为等待中时才能变更状态
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
// 执行成功回调函数
this.onResolvedCallbacks.forEach((callback) => callback());
}
};
// 定义 reject 函数,用于将 Promise 状态变更为失败
const reject = (reason) => {
// 只有在状态为等待中时才能变更状态
if (this.status === 'pending') {
this.status = 'rejected';
this.reason = reason;
// 执行失败回调函数
this.onRejectedCallbacks.forEach((callback) => callback());
}
};
// 执行传入的执行器函数,并传入 resolve 和 reject 函数
try {
executor(resolve, reject);
} catch (error) {
// 如果执行器函数抛出异常,将 Promise 状态变更为失败
reject(error);
}
}
// then 方法用于注册成功和失败的回调函数
then(onFulfilled, onRejected) {
// 创建一个新的 Promise 对象
const newPromise = new MyPromise((resolve, reject) => {
// 封装成功时执行的函数
const fulfilledWrapper = () => {
try {
// 执行成功回调,并将结果传递给新 Promise 的 resolve
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
// 如果执行回调函数抛出异常,将新 Promise 状态变更为失败
reject(error);
}
};
// 封装失败时执行的函数
const rejectedWrapper = () => {
try {
// 执行失败回调,并将原因传递给新 Promise 的 reject
const result = onRejected(this.reason);
reject(result);
} catch (error) {
// 如果执行回调函数抛出异常,将新 Promise 状态变更为失败
reject(error);
}
};
// 根据当前状态分别处理
if (this.status === 'fulfilled') {
// 如果状态为成功,立即执行成功回调
fulfilledWrapper();
} else if (this.status === 'rejected') {
// 如果状态为失败,立即执行失败回调
rejectedWrapper();
} else if (this.status === 'pending') {
// 如果状态为等待中,将成功和失败回调存储起来,等待执行
this.onResolvedCallbacks.push(fulfilledWrapper);
this.onRejectedCallbacks.push(rejectedWrapper);
}
});
// 返回新 Promise 对象,实现链式调用
return newPromise;
}
}
这是一个简单的 Promise 实现,包含了基本的状态管理、执行器函数执行、then 方法注册回调函数以及链式调用的功能。当然,实际的 Promise 还包含了更多的细节和边缘情况处理,但以上代码足以帮助大家理解 Promise 的基本原理。
希望这篇文章能够帮助你更深入地理解 Promise,并在实际项目中更灵活地运用它。