JS中Promise的类式实现写法
2024-03-09 本文已影响0人
硅谷干货
Promise在面试中也会经常遇到,以下是我的手写实现方式,经测试效果不错,小伙伴们们可以直接拷贝使用。
类式定义方式
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);
});
输出如下:
image.png