Promise在面試中也會經(jīng)常遇到,以下是我的手寫實現(xiàn)方式掐禁,經(jīng)測試效果不錯怜械,小伙伴們們可以直接拷貝使用。
類式定義方式
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);
});
輸出如下: