【JavaScript】手写Promise
手写一个简单的Promise可以包含以下几个状态和方法:pending
、fulfilled
、rejected
,以及then
、catch
方法。
class SimplePromise {
constructor(executor) {
this.status = 'pending'; // 初始状态为pending
this.value = undefined; // 保存resolve的值
this.reason = undefined; // 保存reject的原因
const resolve = (value) => {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
}
};
const reject = (reason) => {
if (this.status === 'pending') {
this.status = 'rejected';
this.reason = reason;
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.status === 'fulfilled') {
onFulfilled(this.value);
}
if (this.status === 'rejected') {
onRejected(this.reason);
}
}
catch(onRejected) {
this.then(undefined, onRejected);
}
}
// 使用示例
const promise = new SimplePromise((resolve, reject) => {
// 异步操作
setTimeout(() => {
// resolve(42); // 可以更改为其他操作
// reject('Operation failed');
}, 1000);
});
promise.then(
(value) => console.log('Resolved:', value),
(reason) => console.log('Rejected:', reason)
);
这个简易版本的SimplePromise
类实现了then
和catch
方法,以及内部的resolve
和reject
逻辑。这个实现没有考虑链式调用和并行处理,但足以演示基本的Promise行为。
评论已关闭