直接上代码
class MyPromise {
#state = "pending";
#callbacks = [];
#result = undefined;
constructor(executor) {
try {
executor(this.#resolve.bind(this), this.#reject.bind(this));
} catch (err) {
this.#reject(err);
}
}
#resolve(result) {
this.#state = "fulfilled";
this.#result = result;
for (const callback of this.#callbacks) {
callback.onfulfilled(this.#result);
}
}
#reject(reason) {
this.#state = "rejected";
this.#result = reason;
for (const callback of this.#callbacks) {
callback.onrejected(this.#result);
}
}
then(onfulfilled, onrejected) {
return new MyPromise((resolve, reject) => {
if (this.#state === "fulfilled") {
if (typeof onfulfilled === "function") {
const result = onfulfilled(this.#result);
if (result instanceof MyPromise) {
result.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(result);
}
} else {
resolve(this.#result);
}
}
if (this.#state === "rejected") {
if (typeof onrejected === "function") {
const result = onrejected(this.#result);
if (result instanceof MyPromise) {
result.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(result);
}
} else {
reject(this.#result);
}
}
if (this.#state === "pending") {
this.#callbacks.push({
onfulfilled: () => {
if (typeof onfulfilled === "function") {
const result = onfulfilled(this.#result);
if (result instanceof MyPromise) {
result.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(result);
}
} else {
resolve(this.#result);
}
},
onrejected: () => {
if (typeof onrejected === "function") {
const result = onrejected(this.#result);
if (result instanceof MyPromise) {
result.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(result);
}
} else {
reject(this.#result);
}
},
});
}
});
}
catch(onrejected) {
this.then(undefined, onrejected);
}
static resolve(data) {
return new MyPromise((resolve, reject) => {
if (data instanceof MyPromise) {
data.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(data);
}
});
}
static reject(data) {
return new MyPromise((resolve, reject) => {
reject(data);
});
}
static all(promises) {
return new MyPromise((resolve, reject) => {
let count = 0;
let fulfilledCount = 0;
let resultList = [];
for (const promise of promises) {
let index = count;
promise.then(
(res) => {
resultList[index] = res;
fulfilledCount++;
if (fulfilledCount === count) {
resolve(resultList);
}
},
(err) => {
reject(err);
}
);
count++;
}
if (count === 0) {
resolve([]);
}
});
}
}