Promise 是一个表示异步操作完成或失败的对象。实现一个简单的 Promise,可以按照以下步骤进行:
- 定义 Promise 函数,它接受一个 executor 函数作为参数。
- 在 Promise 函数内部,定义初始状态为‘Pending’,初始值为 undefined 的变量 result,以及保存所有成功回调函数和失败回调函数的数组。
- 定义 resolve 和 reject 函数,分别用于改变 Promise 对象的状态和结果值,并执行对应的回调函数。
- 在 executor 函数内部调用 resolve 和 reject 函数,并将异步操作的结果作为参数传递给它们。
- 定义 then 函数,它接受两个回调函数作为参数,分别用于处理 Promise 对象的状态为 resolved 或 rejected 的情况。
- 将 then 函数内部的回调函数加入到保存成功回调和失败回调的数组中。
以下是一个简单的实现:
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.result = undefined;
this.successCallbacks = [];
this.errorCallbacks = [];
const resolve = value => {
if (this.state === 'pending') {
this.state = 'resolved';
this.result = value;
this.successCallbacks.forEach(callback => callback(this.result));
}
}
const reject = reason => {
if (this.state === 'pending') {
this.state = 'rejected';
this.result = reason;
this.errorCallbacks.forEach(callback => callback(this.result));
}
}
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(successCallback, errorCallback) {
if (this.state === 'resolved') {
successCallback(this.result);
} else if (this.state === 'rejected') {
errorCallback(this.result);
} else {
this.successCallbacks.push(successCallback);
this.errorCallbacks.push(errorCallback);
}
}
}