在async函数中实现并行请求需用Promise.all()同时发起,而非await逐个等待;错误处理可选Promise.allSettled()或单个.catch();需取消时配合AbortController。

在 async 函数中处理多个并行请求,核心是用 Promise.all() 而不是 await 逐个等待 —— 否则就变成串行了,失去并行意义。
用 Promise.all() 同时发起所有请求
把所有 fetch(或 axios 等)调用直接写进 Promise.all() 的数组里,它们会真正并发执行:
✅ 正确(并行):
async function fetchUserData() {
const [userRes, postsRes, commentsRes] = await Promise.all([
fetch('/api/user'),
fetch('/api/posts'),
fetch('/api/comments')
]);
const user = await userRes.json();
const posts = await postsRes.json();
const comments = await commentsRes.json();
return { user, posts, comments };
}
注意错误处理:Promise.all() 遇错即停
Promise.all() 只要有一个 Promise reject,整个就会失败,其他还在跑的请求不会自动取消(但浏览器通常会继续完成)。如需容错,有几种常用方式:
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
立即学习“Java免费学习笔记(深入)”;
- 用 Promise.allSettled():等全部结束,返回每个 Promise 的 {status, value/reason},适合“尽力而为”场景
- 对单个请求加 .catch() 包裹,转成 always-resolve 的 Promise(例如返回 null 或默认值)
- 需要强一致性且任一失败就中断时,保留 Promise.all(),再配合 try/catch 捕获整体错误
需要取消请求?手动 AbortController
Promise.all() 本身不支持取消,但现代 fetch 支持 AbortController。如需中途取消所有请求,可统一传入同一个 signal:
async function fetchWithAbort() {
const controller = new AbortController();
// 10秒后自动取消
setTimeout(() => controller.abort(), 10000);
try {
const [userRes, postsRes] = await Promise.all([
fetch('/api/user', { signal: controller.signal }),
fetch('/api/posts', { signal: controller.signal })
]);
return [await userRes.json(), await postsRes.json()];
} catch (err) {
if (err.name === 'AbortError') {
console.log('请求被取消');
}
throw err;
}
}
别混淆:await 多次 ≠ 并行
下面写法是串行的,耗时是三个请求之和:
// ❌ 错误(串行)
const userRes = await fetch('/api/user');
const postsRes = await fetch('/api/posts'); // 等 user 完了才发
const commentsRes = await fetch('/api/comments'); // 再等 posts 完了才发
只要用了 await 一行接一行,就不是并行 —— 无论函数是不是 async。

















