推荐答案
// www.javascriptcn.com code example
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(callback => callback(value));
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = reason;
this.onRejectedCallbacks.forEach(callback => callback(reason));
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value);
} else if (this.state === 'rejected') {
onRejected(this.value);
} else {
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
}
return this;
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
// 示例用法
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
promise.then((value) => {
console.log(value); // 输出: Success!
}).catch((error) => {
console.error(error);
});本题详细解读
1. Promise 的基本结构
MyPromise 类是一个简单的 Promise 实现。它包含以下几个关键部分:
- state: 表示 Promise 的当前状态,可以是
pending、fulfilled或rejected。 - value: 存储 Promise 的结果值或拒绝原因。
- onFulfilledCallbacks 和 onRejectedCallbacks: 用于存储
then方法中传入的回调函数,以便在 Promise 状态改变时调用。
2. 构造函数
构造函数接收一个 executor 函数,该函数立即执行,并传入 resolve 和 reject 两个函数作为参数。resolve 和 reject 分别用于将 Promise 的状态从 pending 改为 fulfilled 或 rejected,并触发相应的回调函数。
3. then 方法
then 方法用于注册 onFulfilled 和 onRejected 回调函数。如果 Promise 已经处于 fulfilled 或 rejected 状态,则立即调用相应的回调函数。否则,将回调函数存储在 onFulfilledCallbacks 或 onRejectedCallbacks 中,等待状态改变时调用。
4. catch 方法
catch 方法是 then 方法的语法糖,专门用于处理 rejected 状态的情况。
5. 示例用法
在示例中,我们创建了一个 MyPromise 实例,并在 1 秒后调用 resolve 方法。then 方法中的回调函数会在 resolve 被调用时执行,输出 Success!。
6. 注意事项
- 这个实现是一个简化的版本,不支持链式调用(即
then方法返回一个新的 Promise)。 - 实际使用中,Promise 的实现会更加复杂,包括对异步操作的支持、链式调用、错误处理等。
通过这个简单的实现,可以更好地理解 Promise 的工作原理和基本结构。