类式定义方式
class MyPromise {
constructor(executor) {
this.status = "pending";
this.value = undefined;
this.reason = undefined;
let resolveFn = (value) => {
if (this.status === "pending") {
this.status = "resolve";
this.value = value;
}
};
let rejectFn = (reason) => {
if (this.status === "pending") {
this.status = "reject";
this.reason = reason;
}
};
try {
executor(resolveFn, rejectFn);
} catch (error) {
rejectFn(error);
}
}
then(onFulfilled, onRejected) {
if (this.status === "resolve") {
onFulfilled(this.value);
}
if (this.status === "reject") {
onRejected(this.reason);
}
}
}
测试和打印
new MyPromise((resolve, reject) => {
resolve("123");
}).then((res) => {
console.log(res);
});
输出如下: