then方法只直接接收成功回调,失败回调应优先使用catch处理;其两个参数分别为成功时执行的函数和失败时执行的函数,但后者不常用。

在 JavaScript 中,then 方法用于处理 Promise 的成功(fulfilled)和失败(rejected)状态,但它**只直接接收成功回调**;失败回调需通过第二个参数或更推荐的 catch 来处理。
then 的两个参数:成功回调 + 失败回调(不常用)
then 接收两个可选函数参数:
- 第一个参数:Promise 成功时执行的函数(接收 resolved 值)
- 第二个参数:Promise 失败时执行的函数(接收 rejected reason)
例如:
fetch('/api/data')
.then(
response => console.log('成功:', response),
error => console.error('失败:', error) // 这里能捕获 fetch 抛出的网络错误
);更推荐:用 then + catch 分离关注点
将成功逻辑和错误处理解耦,语义更清晰,也便于统一错误处理:
-
then只负责“成功后的处理” -
catch专门捕获前面任意环节(包括then内部)抛出的错误
例如:
fetch('/api/data')
.then(response => {
if (!response.ok) throw new Error('HTTP 错误');
return response.json();
})
.then(data => console.log('数据:', data))
.catch(error => console.error('出错了:', error));注意:then 中抛错会跳转到最近的 catch
如果在 then 的成功回调里主动 throw 或返回一个被 reject 的 Promise,后续的 then 会被跳过,控制权交给 catch:
Promise.resolve(1)
.then(x => {
throw new Error('手动报错');
})
.then(x => console.log('这行不会执行'))
.catch(err => console.log('捕获到:', err.message)); // 输出:手动报错小结:怎么注册回调?
- 成功回调:始终作为
then(onFulfilled)的第一个参数 - 失败回调:建议用
.catch(onRejected),而非then(null, onRejected) - 链式调用中,
catch能捕获它之前所有环节的异常(包括上一个then里的同步错误和异步 reject)


















