Promise.prototype.then 返回新 Promise 实现链式调用,onFulfilled/onRejected 的返回值决定下一个 then 的输入或错误传递;推荐用 .catch 统一处理错误。

Promise.prototype.then 通过返回一个新的 Promise 实例来实现链式调用,允许你依次注册成功(onFulfilled)和失败(onRejected)回调,并自然传递结果或错误。
一、then 的基本签名与返回值
promise.then(onFulfilled, onRejected) 接收两个可选函数参数:
- onFulfilled:当 promise 成功(fulfilled)时执行,接收上一个 promise 的 resolved 值;
- onRejected:当 promise 失败(rejected)时执行,接收上一个 promise 的 rejection reason。
关键点在于:每次调用 then 都会返回一个新 Promise,它的状态由 onFulfilled 或 onRejected 的执行结果决定。这正是链式注册的基础。
二、链式注册成功回调(连续 .then)
多个 .then() 串连时,每个成功回调的返回值会作为下一个 then 中 onFulfilled 的输入:
Promise.resolve(1) .then(x => x + 1) // 返回 2 → 下个 then 收到 2 .then(x => x * 2) // 返回 4 → 下个 then 收到 4 .then(x => console.log(x)); // 输出 4
如果某个 then 回调返回一个 Promise,链会等待它 settle 后再继续:
Promise.resolve('a')
.then(str => new Promise(r => setTimeout(() => r(str + 'b'), 100)))
.then(str => console.log(str)); // 100ms 后输出 'ab'
三、链式注册失败回调(捕获与传递错误)
错误不会自动跨 then 传播,需显式处理:
- 若上一个 Promise 被 reject,且当前 then 没传 onRejected,则错误穿透到下一个 then 的 onRejected;
- 若当前 then 提供了 onRejected 并抛出异常或返回 rejected Promise,错误继续向后传递;
- 若 onRejected 返回普通值(非 Promise),则后续 then 的 onFulfilled 会被调用(错误被“消化”)。
示例:
Promise.reject('err')
.then(null, reason => {
console.log('捕获:', reason); // 输出 'err'
return 'recovered';
})
.then(val => console.log('恢复后:', val)); // 输出 '恢复后: recovered'
四、推荐写法:用 catch 替代第二个参数
为提高可读性和避免错误穿透遗漏,建议将失败处理统一移到链末尾:
someAsyncOperation()
.then(result => process(result))
.then(data => save(data))
.catch(error => {
console.error('任一环节出错:', error);
});
等价于在每个 then 后都写 .then(undefined, handleError),但更简洁、不易出错。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











