async函数是promise的语法糖,自动返回promise,用await替代.then()使代码更同步化、可读性提升,支持try/catch统一错误处理,并行请求需用promise.all或allsettled。

用 async 函数替代 Promise 链,核心是把“嵌套的 .then()”变成“顺序写的 await 表达式”,代码更接近同步逻辑,可读性和维护性明显提升。
async 函数本质就是 Promise 的语法糖
async 函数自动返回一个 Promise,函数体内遇到 await 会暂停执行(但不阻塞线程),等右侧的 Promise settle 后再继续。不需要手动调用 .then() 或 .catch(),错误也能用 try/catch 统一处理。
-
async function foo() { return 123 }等价于返回Promise.resolve(123) -
await只能在async函数内部使用 -
await后面可以是 Promise、任意值,或一个 thenable 对象
把多层 .then() 改成 await 顺序调用
比如原来这样写:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
fetch('/api/user')
.then(res => res.json())
.then(user => fetch(`/api/posts?uid=${user.id}`))
.then(res => res.json())
.then(posts => console.log(posts))
.catch(err => console.error(err));
改成 async/await 后更清晰直观:
async function loadUserPosts() {
try {
const userRes = await fetch('/api/user');
const user = await userRes.json();
const postsRes = await fetch(`/api/posts?uid=${user.id}`);
const posts = await postsRes.json();
console.log(posts);
} catch (err) {
console.error(err);
}
}
并行请求别忘了用 Promise.all
如果多个请求互不依赖,不要傻傻地 await 一个接一个——那会变串行,拖慢速度。该并行时就用 Promise.all 包一层:
async function loadBoth() {
try {
// ✅ 并行发起
const [user, posts] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/posts').then(r => r.json())
]);
console.log(user, posts);
} catch (err) {
console.error(err);
}
}
- 注意:Promise.all 中任意一个失败,整个就会 reject;如需“全都要,失败也不中断”,可用
Promise.allSettled - 也可以先
await前置数据,再Promise.all后续并行请求,灵活组合
错误处理统一用 try/catch,比 .catch 更自然
链式写法里,.catch() 可能捕获前面任意环节的错误,位置容易写错;而 try/catch 范围明确,语义直接:
async function riskyTask() {
try {
const data = await fetch('/api/data').then(r => r.json());
const result = await process(data); // 这里也可能 throw
return result;
} catch (err) {
// 所有 await 失败、或 process 抛异常,都进这里
console.warn('任务失败:', err.message);
throw err; // 可选择重新抛出
}
}
- 如果只想捕获某一步的错误,可以单独给那步加
try/catch,不影响后续 - 避免在
await后直接调用可能 throw 的同步函数却不包裹 —— 它不会被外层catch捕获
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










