用js写出模拟promise
要在JavaScript中模拟一个简单的Promise实现,你需要理解Promise的基本行为和状态管理。一个Promise有三种状态:pending
(进行中)、fulfilled
(已成功)和rejected
(已失败)。它还需要支持then
方法来处理成功和失败的回调。
以下是一个简化版的Promise实现:
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(callback => callback(this.value));
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback(this.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.reason);
} else if (this.state === 'pending') {
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
}
}
}
// 测试代码
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功');
}, 1000);
});
promise.then(
value => {
console.log('Resolved:', value);
},
reason => {
console.log('Rejected:', reason);
}
);
这个简化版的Promise实现包括以下几个部分:
this.state
来管理Promise的状态。this.onFulfilledCallbacks
和this.onRejectedCallbacks
分别存储成功和失败的回调函数。resolve
和reject
函数:用于改变Promise的状态并执行相应的回调。then
方法:用于注册成功和失败的回调函数。这个实现是一个简化版,实际的Promise实现要复杂得多,包括链式调用、错误处理、异步执行