
本文详解如何为自定义 Promise 类添加链式 catch() 方法,通过分离成功回调与失败回调、确保 then() 返回 this 实现方法链,并演示完整可运行的轻量级 Promise 实现。
本文详解如何为自定义 promise 类添加链式 `catch()` 方法,通过分离成功回调与失败回调、确保 `then()` 返回 `this` 实现方法链,并演示完整可运行的轻量级 promise 实现。
要为自定义 Promise 类(如 MyPromise)正确支持 .catch(),核心在于两点:状态分离与链式调用支持。当前代码中,#resolve 和 #reject 共用同一个 this.cb 回调,导致错误无法被独立捕获;同时 then() 未返回 this,使 .catch() 无法链式调用。
以下是优化后的完整实现:
class MyPromise {
constructor(initFunction) {
// 成功回调与失败回调解耦
this.onFulfilled = () => {};
this.onRejected = () => {};
initFunction(
this.#resolve.bind(this),
this.#reject.bind(this)
);
}
#resolve(value) {
this.onFulfilled(value);
}
#reject(reason) {
this.onRejected(reason);
}
then(onFulfilled) {
this.onFulfilled = onFulfilled;
return this; // ✅ 支持链式调用(如 .then(...).catch(...))
}
catch(onRejected) {
this.onRejected = onRejected;
return this; // ✅ 同样返回 this,便于后续链式扩展(如 .catch(...).finally(...))
}
}
// 使用示例
const add = (a, b) => {
return new MyPromise((resolve, reject) => {
setTimeout(() => {
if (typeof a !== 'number' || typeof b !== 'number') {
reject('Invalid params: both arguments must be numbers');
} else {
resolve(a + b);
}
}, 1000);
});
};
// 正确调用:成功时执行 then,失败时触发 catch
add(2, 5).then(result => console.log('Result:', result));
// 输出:Result: 7(1秒后)
add("hello", 3).then(result => console.log(result))
.catch(error => console.error('Caught error:', error));
// 输出:Caught error: Invalid params: both arguments must be numbers(1秒后)
⚠️ 关键注意事项:
- then() 和 catch() 必须返回 this,否则链式调用会中断;
- #resolve 和 #reject 应分别触发各自对应的回调,不可混用;
- 当前实现是“新手版”,不支持异步任务队列、Promise A+ 状态机(pending/fulfilled/rejected)、值穿透或 Promise.resolve() 等高级特性;
- 真实 Promise 中,catch() 本质是 then(null, onRejected) 的语法糖——若需进阶实现,建议后续引入状态管理(this.state = 'pending')及微任务调度(queueMicrotask)。
掌握这一基础结构,是你深入理解 Promise 原理与手写 Promise/A+ 兼容实现的重要起点。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











