返回
手写一个 Promise,感受 asynchronous
前端
2023-09-08 06:25:58
Promise 是 JavaScript 中用于处理异步操作的工具,它提供了 then() 和 catch() 方法来处理成功和失败的情况。要实现自己的 Promise,我们可以创建一个对象,它具有 pending、resolved 和 rejected 三种状态,并且包含 then() 和 catch() 方法。
pending 状态表示 Promise 还没有完成,resolved 状态表示 Promise 已成功完成,rejected 状态表示 Promise 已失败。
class MyPromise {
constructor(executor) {
this.state = "pending";
this.value = undefined;
this.error = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
try {
executor(
(value) => {
this.resolve(value);
},
(error) => {
this.reject(error);
}
);
} catch (error) {
this.reject(error);
}
}
resolve(value) {
if (this.state !== "pending") {
return;
}
this.state = "resolved";
this.value = value;
this.onFulfilledCallbacks.forEach((callback) => {
callback(this.value);
});
}
reject(error) {
if (this.state !== "pending") {
return;
}
this.state = "rejected";
this.error = error;
this.onRejectedCallbacks.forEach((callback) => {
callback(this.error);
});
}
then(onFulfilled, onRejected) {
if (this.state === "pending") {
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
} else if (this.state === "resolved") {
onFulfilled(this.value);
} else if (this.state === "rejected") {
onRejected(this.error);
}
return new MyPromise((resolve, reject) => {
this.then(
(value) => {
try {
const result = onFulfilled(value);
resolve(result);
} catch (error) {
reject(error);
}
},
(error) => {
try {
const result = onRejected(error);
resolve(result);
} catch (error) {
reject(error);
}
}
);
});
}
catch(onRejected) {
return this.then(undefined, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally();
return value;
},
(error) => {
onFinally();
return error;
}
);
}
}
这个手写的 Promise 实现了then、catch、finally等方法,可以用于各种异步处理的需求。
此外,你还可以添加额外的特性,比如超时处理、取消处理等。这些都会使你的 Promise 更加完善。