- 保证三种状态
- 保证状态的流转是不可逆的
- 保证then可以多次调用=》需要一个数组保存callback,(包含resolve和reject的callback数组)
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MyPromise {
status = PENDING;
value = null;
reason = null;
resolveCallback;
rejectCallback;
constructor (executer) {
if (!executer) {
return;
}
executer(this.resolve, this.reject);
}
resolve = (v) => {
if (this.status === PENDING) {
this.status = FULFILLED;
this.value = v;
this.resolveCallback?.forEach((cb) => {
cb(v);
});
this.resolveCallback = [];
}
};
reject = (e) => {
if (this.status === PENDING) {
this.status = REJECTED;
this.reason = e;
this.rejectCallback?.forEach((cb) => {
cb(e);
});
this.rejectCallback = [];
}
};
then (onSuccess, onError) {
const _this = this;
return new MyPromise((res, rej) => {
if (this.status === FULFILLED) {
onSuccess(this.value);
}
if (_this.status === REJECTED) {
onError(this.reason);
}
if (this.status === PENDING) {
this.resolveCallback.push(onSuccess);
this.rejectCallback.push(onError);
}
});
}
}