箭头函数简化 promise 链:省略 function、括号和 return,提升紧凑性与可读性;适用于简单转换、扁平链式调用、词法 this/闭包复用及 async/await 辅助场景,但复杂逻辑仍需命名函数。
直接用箭头函数写 .then() 回调,能省掉 function 关键字、括号和 return(单表达式时),让 promise 链更紧凑、逻辑更聚焦。
用表达式体替代语句体
当处理简单转换(如提取字段、格式化数据)时,优先用单表达式写法:
-
.then(res => res.data)比.then(function(res) { return res.data; })少 18 个字符,且一眼看清意图 -
.then(user => user.id)、.then(str => str.trim())这类操作天然适合表达式体 - 注意:只有返回值需被下一级接收时才依赖自动返回;若只是副作用(如打日志),仍要写
{ console.log(...); return ...; }
避免嵌套,保持扁平链路
箭头函数配合链式调用,天然抑制“回调地狱”倾向:
- 错误示范:
fetch('/api/user').then(res => res.json()).then(user => { fetch(`/api/posts?uid=${user.id}`).then(...); });—— 又出现嵌套 - 正确写法:
fetch('/api/user').then(res => res.json()).then(user => fetch(`/api/posts?uid=${user.id}`)).then(res => res.json()).then(posts => ({ user, posts })) - 每步只做一件事,返回新 Promise,整条链保持线性阅读顺序
利用词法 this 和闭包简化上下文传递
箭头函数不绑定自己的 this,也不需要 bind 或中间变量保存上下文:
- 在类方法中发起请求时:
loadData = () => fetch('/data').then(res => res.json()).then(data => this.setState({ data }))——this自动指向组件实例 - 外部变量(如 token、配置)可直接访问,无需
use(PHP)或bind(JS)显式传入:const token = 'abc'; api.get().then(res => authCheck(res, token)) - 对比普通函数:
.then(function(res) { return authCheck(res, token); }.bind(this))明显冗长
组合 async/await 时仍可沿用箭头风格
即便迁移到 async/await,箭头函数在事件处理器或高阶函数中仍有价值:
- 按钮点击触发异步流程:
onClick={() => fetchData().then(showResult).catch(handleError)} - 封装重试逻辑:
const retry = (fn, times) => times > 0 ? fn().catch(() => retry(fn, times - 1)) : Promise.reject('max retries'),内部依然用箭头保持简洁 - 不要为了用箭头而强行链式;如果某步逻辑复杂(含条件判断、多 await),就拆成命名函数,可读性优先










