promise基本功能点
- 创建对象的时候,传入一个回调,并且能够接收成功、失败状态设置两个参数
- 能够通过then方法调用,根据状态调用成功或者失败回调,then后面还可以连续使用then,因此then方法需要返回与当前状态一致的promise
实现promise基本功能
class MyPromise = {
constructor(executor) {
this.state = 'pending'
this.value = undefined
this.handlers = []
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.handlers.forEach(handler => this.executeHandler(handler));
this.handlers = [];
}
}
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = reason;
this.handlers.forEach(handler => this.executeHandler(handler));
this.handlers = [];
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
executeHandler(handler) {
const { onFulfilled, onRejected, resolve, reject } = handler;
if (this.state === 'fulfilled') {
if (typeof onFulfilled === 'function') {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
} else {
resolve(this.value);
}
} else if (this.state === 'rejected') {
if (typeof onRejected === 'function') {
try {
const result = onRejected(this.value);
resolve(result);
} catch (error) {
reject(error);
}
} else {
reject(this.value);
}
}
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
const handler = {
onFulfilled,
onRejected,
resolve,
reject
};
if (this.state === 'pending') {
this.handlers.push(handler);
} else {
this.executeHandler(handler);
}
});
}
}