实现一个简易版的Promise。这个实现涵盖了Promise的基本功能,包括状态管理、then方法、以及异步解析。以下是代码实现:
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(value));
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback(reason));
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
return new MyPromise((resolve, reject) => {
const fulfilledHandler = (value) => {
try {
const result = onFulfilled(value);
resolve(result);
} catch (error) {
reject(error);
}
};
const rejectedHandler = (reason) => {
try {
const result = onRejected(reason);
resolve(result);
} catch (error) {
reject(error);
}
};
if (this.state === 'fulfilled') {
setTimeout(() => fulfilledHandler(this.value), 0);
} else if (this.state === 'rejected') {
setTimeout(() => rejectedHandler(this.reason), 0);
} else if (this.state === 'pending') {
this.onFulfilledCallbacks.push(fulfilledHandler);
this.onRejectedCallbacks.push(rejectedHandler);
}
});
}
}
这个实现包含以下主要特性:
- 状态管理: Promise有三种状态 - pending, fulfilled, 和 rejected。
- 值存储: 保存fulfilled状态的值或rejected状态的原因。
- then方法: 允许链式调用和异步操作。
- 回调队列: 当Promise还在pending状态时,存储then中的回调。
- 异常处理: 捕获执行器和回调中的错误。
使用示例:
const p = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
p.then(
value => console.log(value),
reason => console.error(reason)
).then(
() => console.log('This runs after the first then')
);
关注微信公众号温暖前端,不定期分享前端知识点和前端资料↓↓↓