在 JavaScript 中,Promise 是一种常用的异步编程模型,可以让我们更加方便地处理异步操作。以下是一个简单的 Promise 实现。
function Promise(executor) {
// 初始化 Promise 状态、结果和回调函数列表
this.state = 'pending';
this.result = undefined;
this.callbacks = [];
// 定义 resolve 函数
const resolve = (value) => {
if (this.state !== 'pending') {
return;
}
// 修改 Promise 状态和结果
this.state = 'fulfilled';
this.result = value;
// 依次执行回调函数列表中的回调函数
this.callbacks.forEach((callback) => {
callback.onFulfilled(value);
});
};
// 定义 reject 函数
const reject = (reason) => {
if (this.state !== 'pending') {
return;
}
// 修改 Promise 状态和结果
this.state = 'rejected';
this.result = reason;
// 依次执行回调函数列表中的回调函数
this.callbacks.forEach((callback) => {
callback.onRejected(reason);
});
};
try {
// 执行传入的 executor 函数,并传入 resolve 和 reject 函数作为参数
executor(resolve, reject);
} catch (error) {
// 如果 executor 函数抛出异常,则使用 reject 函数处理异常
reject(error);
}
}
// 定义 Promise 的 then 方法
Promise.prototype.then = function (onFulfilled, onRejected) {
return new Promise((resolve, reject) => {
// 定义回调函数对象
const callback = {
onFulfilled: (value) => {
try {
// 执行 onFulfilled 回调函数,并获取返回值 result
const result = onFulfilled(value);
// 如果 result 是 Promise 对象,则等待其状态改变后再执行 resolve 或 reject 函数
if (result instanceof Promise) {
result.then(resolve, reject);
} else {
// 否则直接调用 resolve 函数,并将 result 作为参数传入
resolve(result);
}
} catch (error) {
// 如果执行 onFulfilled 回调函数时抛出异常,则使用 reject 函数处理异常
reject(error);
}
},
onRejected: (reason) => {
try {
// 执行 onRejected 回调函数,并获取返回值 result
const result = onRejected(reason);
// 如果 result 是 Promise 对象,则等待其状态改变后再执行 resolve 或 reject 函数
if (result instanceof Promise) {
result.then(resolve, reject);
} else {
// 否则直接调用 reject 函数,并将 result 作为参数传入
reject(result);
}
} catch (error) {
// 如果执行 onRejected 回调函数时抛出异常,则使用 reject 函数处理异常
reject(error);
}
},
};
// 如果 Promise 状态为 pending,则将回调函数对象添加到回调函数列表中
if (this.state === 'pending') {
this.callbacks.push(callback);
} else if (this.state === 'fulfilled') {
// 如果 Promise 状态为 fulfilled,则立即执行 onFulfilled 回调函数,并将结果作为参数传入
callback.onFulfilled(this.result);
} else if (this.state === 'rejected') {
// 如果 Promise 状态为 rejected,则立即执行 onRejected 回调函数,并将结果作为参数传入
callback.onRejected(this.result);
}
});
};
// 定义 catch 函数进行异常捕获
Promise.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};
在上述代码中,Promise 构造函数接受一个参数 executor,它是一个函数,用于执行异步操作。构造函数会创建一个 Promise 实例,并初始化 state、result 和 callbacks 属性。
在构造函数中,我们定义了两个函数 resolve 和 reject,它们被传递给 executor,用于在异步操作完成时分别处理成功和失败的结果。如果 Promise 实例的状态已经变为 fulfilled 或 rejected,那么 resolve 和 reject 函数就不会再执行。
在 resolve 和 reject 函数中,我们将 Promise 实例的状态分别设置为 fulfilled 或 rejected,将结果保存在 result 属性中,并依次调用 callbacks 列表中的回调函数。
在 then 方法中,我们首先创建一个新的 Promise 实例,并定义 onFulfilled 和 onRejected 回调函数,这两个函数分别处理 Promise 实例在 fulfilled 和 rejected 状态下的处理逻辑。如果 onFulfilled 或 onRejected 函数返回的结果是 Promise 实例,那么我们将返回的 Promise 实例的状态和结果与当前 Promise 实例的状态和结果保持一致。如果返回的不是 Promise 实例,则直接将返回值传递给新的 Promise 实例。
在 catch 方法中,我们调用 then 方法并将 onFulfilled 参数设置为 null,将 onRejected 参数设置。