async/await 是替代 Promise 链最直接彻底的解法,将异步逻辑转为线性结构、消除右偏缩进,错误统一用 try/catch 处理;需避免 await 后接 .then、合理拆分函数、警惕未 await 的隐式 Promise。

用 async/await 替代 Promise 链,是最直接、最彻底的解法。它把异步逻辑拉回“看起来像同步”的线性结构,缩进自然归零。
用 async/await 重写链式调用
Promise 链层层嵌套(.then().then().catch())导致右偏、难读;async/await 把每个异步步骤写成普通语句,错误统一用 try/catch 捕获。
例如:
- 原来:
.then(res => res.json())
.then(user => fetch(`/api/posts?uid=${user.id}`))
.then(res => res.json())
.then(posts => render({ user, posts }))
.catch(err => showError(err));
- 现在:
try {
const res1 = await fetch('/api/user');
const user = await res1.json();
const res2 = await fetch(`/api/posts?uid=${user.id}`);
const posts = await res2.json();
render({ user, posts });
} catch (err) {
showError(err);
}
}
避免在 await 后立即 .then() 或嵌套 async 函数
常见误区是“半迁移到 async/await”,比如:await fetch(...).then(...) 或在循环里写 arr.map(x => async () => {...}),这仍会制造隐式嵌套或 Promise 数组,缩进虽少但逻辑混乱。
立即学习“Java免费学习笔记(深入)”;
正确做法:
- 每个 await 后直接处理结果,不接 .then
- 并行请求用
Promise.all([await a(), await b()])→ 改为await Promise.all([a(), b()]) - 需要逐个处理数组时,用 for...of 而非 map + async:更清晰、可中断、无缩进累积
合理拆分 async 函数,控制单函数复杂度
一个超长的 async 函数虽然没缩进,但可读性仍差。应按业务语义拆成小函数,每个专注一件事:
async function fetchUser(id) { ... }async function fetchPostsByUser(user) { ... }async function renderPage() { const user = await fetchUser(...); const posts = await fetchPostsByUser(user); ... }
调用链扁平,职责分明,调试和复用也更容易。
警惕隐式 Promise 和未 await 的副作用
缩进没了,不代表异步风险消失。以下情况仍可能引发“逻辑错位”:
- 忘记 await 某个 async 函数调用 → 返回 Promise 对象而非实际值,后续代码可能出错或静默失败
- 在 if/else 或循环中漏写 await → 分支执行顺序失控
- 用 setTimeout 或事件监听器触发异步操作,却没用 await 等待其完成
建议开启 ESLint 规则 require-await 和 no-return-await,配合 TypeScript 的类型提示,能提前暴露大部分遗漏 await 的问题。


















