then方法用于处理Promise成功状态并支持链式调用,每次返回新Promise;需显式return以传递值,错误需用catch捕获。

在 JavaScript 中,then 方法用于处理 Promise 成功(fulfilled)时的返回值,并支持链式调用——每次 then 返回一个新的 Promise,让后续操作可以继续接续。
基本用法:接收成功结果并返回新值或新 Promise
then 接收一个函数作为参数,该函数会拿到上一个 Promise 的成功结果。你可以直接返回普通值,也可以返回一个新的 Promise:
- 返回普通值(如字符串、数字、对象):下一级
then会立即收到该值 - 返回 Promise:下一级
then会等待它完成后再执行
例如:
fetch('/api/user').then(res => res.json()).then(user => console.log(user.name));链式传递:每个 then 都可独立处理和转换数据
链式调用的关键在于“每个 then 处理前一个的结果,并产出下一个需要的数据”。中间步骤可以过滤、格式化、组合或发起新请求:
立即学习“Java免费学习笔记(深入)”;
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 第一个
then解析响应体 - 第二个
then提取用户 ID 并请求详情 - 第三个
then合并信息并渲染
示例:
fetch('/api/posts').then(res => res.json())
.then(posts => posts.slice(0, 3))
.then(topPosts => Promise.all(topPosts.map(p => fetch(`/api/users/${p.userId}`).then(r => r.json()))))
.then(authors => console.log('作者列表:', authors));
注意错误不会中断链,但需用 catch 捕获
then 只处理成功状态;如果任意环节抛出错误或返回被拒绝的 Promise,链会跳过后续所有 then 的成功回调,直到遇到 catch 或最后一个 then 的失败回调:
- 推荐在链末尾加
catch统一处理异常 - 也可在某个
then中写两个参数:then(onFulfilled, onRejected)
例如:
fetch('/api/data').then(res => {
if (!res.ok) throw new Error('网络响应失败');
return res.json();
})
.then(data => processData(data))
.catch(err => console.error('出错了:', err.message));
避免常见误区:不要在 then 里忘记 return
如果 then 回调中没写 return,默认返回 undefined,下一级 then 就会收到 undefined,容易导致逻辑断裂:
- ❌ 错误写法:
.then(data => console.log(data))→ 下一个then收到undefined - ✅ 正确写法:
.then(data => { console.log(data); return data; })或.then(data => (console.log(data), data))
箭头函数单表达式隐式返回只适用于纯计算,有副作用(如 log)时建议显式写 return。

















