class MyPromise {
constructor(executor) {
this.state = "pending"; // pending, fulfilled, rejected
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
this.isCancelled = false; // 新增:取消标记
// 保存 resolve 和 reject 的引用,以便在取消时调用
const resolve = (value) => this.resolve(value);
const reject = (reason) => this.reject(reason);
// 提供取消方法给 executor
const cancel = () => this.cancel();
try {
executor(resolve, reject, cancel);
} catch (error) {
reject(error);
}
}
resolve(value) {
if (this.state === "pending" && !this.isCancelled) {
this.state = "fulfilled";
this.value = value;
setTimeout(() => {
if (!this.isCancelled) {
this.onFulfilledCallbacks.forEach((callback) => callback(value));
}
}, 0);
}
}
reject(reason) {
if (this.state === "pending" && !this.isCancelled) {
this.state = "rejected";
this.reason = reason;
setTimeout(() => {
if (!this.isCancelled) {
this.onRejectedCallbacks.forEach((callback) => callback(reason));
}
}, 0);
}
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
const fulfilledHandler = () => {
if (this.isCancelled) return; // 如果已取消,不执行
try {
if (typeof onFulfilled !== "function") {
resolve(this.value);
} else {
const result = onFulfilled(this.value);
if (result instanceof MyPromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
}
} catch (error) {
reject(error);
}
};
const rejectedHandler = () => {
if (this.isCancelled) return; // 如果已取消,不执行
try {
if (typeof onRejected !== "function") {
reject(this.reason);
} else {
const result = onRejected(this.reason);
if (result instanceof MyPromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
}
} catch (error) {
reject(error);
}
};
if (this.state === "fulfilled") {
setTimeout(fulfilledHandler, 0);
} else if (this.state === "rejected") {
setTimeout(rejectedHandler, 0);
} else if (this.state === "pending") {
this.onFulfilledCallbacks.push(fulfilledHandler);
this.onRejectedCallbacks.push(rejectedHandler);
}
});
}
// 新增:取消方法
cancel() {
if (this.state === "pending") {
this.isCancelled = true;
this.onFulfilledCallbacks = []; // 清空回调
this.onRejectedCallbacks = [];
this.state = "cancelled"; // 可选:标记为已取消状态
}
}
static all(promises) {
return new MyPromise((resolve, reject) => {
const results = [];
let completedCount = 0;
const total = promises.length;
if (total === 0) {
resolve(results);
return;
}
promises.forEach((promise, index) => {
MyPromise.resolve(promise).then(
(value) => {
results[index] = value;
completedCount++;
if (completedCount === total) {
resolve(results);
}
},
(reason) => {
reject(reason);
}
);
});
});
}
static race(promises) {
return new MyPromise((resolve, reject) => {
if (promises.length === 0) return;
promises.forEach((promise) => {
MyPromise.resolve(promise).then(
(value) => resolve(value),
(reason) => reject(reason)
);
});
});
}
static resolve(value) {
if (value instanceof MyPromise) return value;
return new MyPromise((resolve) => resolve(value));
}
// 新增:创建可取消的 Promise
static cancellable(executor) {
let cancelFn;
const promise = new MyPromise((resolve, reject, cancel) => {
cancelFn = cancel; // 保存取消函数
executor(resolve, reject, cancel);
});
return {
promise,
cancel: () => cancelFn(),
};
}
}
// 测试可取消 Promise
const { promise, cancel } = MyPromise.cancellable((resolve, reject) => {
console.log("开始执行");
const timeout = setTimeout(() => {
resolve("成功");
}, 2000);
// 在取消时清理资源
return () => clearTimeout(timeout);
});
promise.then(
(value) => console.log("结果:", value), // 如果未取消,输出 "结果: 成功"
(reason) => console.log("失败:", reason)
);
setTimeout(() => {
cancel(); // 500ms 后取消
console.log("已取消");
}, 500);