then方法可多次调用
then方法中的函数为异步执行
class MyPromise {
static PENDING = "pending";
static FULFILLED = "fulfilled";
static REJECTED = "rejected";
#status;
#value;
#reason;
#onFulfilledCallbacks = [];
#onRejectedCallbacks = [];
constructor(executor) {
this.#status = MyPromise.PENDING;
this.#value = undefined;
this.#reason = undefined;
try {
executor(this.#resolve.bind(this), this.#reject.bind(this));
} catch (error) {
this.#reject(error);
}
}
#resolve(value) {
if (this.#status === MyPromise.PENDING) {
this.#status = MyPromise.FULFILLED;
this.#value = value;
this.#onFulfilledCallbacks.forEach((fn) => {
fn(this.#value);
});
}
}
#reject(reason) {
if (this.#status === MyPromise.PENDING) {
this.#status = MyPromise.REJECTED;
this.#reason = reason;
this.#onRejectedCallbacks.forEach((fn) => {
fn(this.#reason);
});
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (value) => value;
onRejected =
typeof onRejected === "function"
? onRejected
: (reason) => {
throw reason;
};
if (this.#status === MyPromise.FULFILLED) {
queueMicrotask(() => {
onFulfilled(this.#value);
});
}
if (this.#status === MyPromise.REJECTED) {
queueMicrotask(() => {
onRejected(this.#reason);
});
}
if (this.#status === MyPromise.PENDING) {
this.#onFulfilledCallbacks.push(() => {
queueMicrotask(() => {
onFulfilled(this.#value);
});
});
this.#onRejectedCallbacks.push(() => {
queueMicrotask(() => {
onRejected(this.#reason);
});
});
}
}
}