promise.all 配合 async/await 是 js 并发请求最常用方式,可并行发起多个异步操作;需用 await 等待其返回的 promise,解构获取结果;失败时用 try/catch 捕获首个错误;动态请求应先 map 出 promise 数组再 all;大量请求需节流控制并发数。

用 Promise.all 配合 async/await 是 JS 中并发请求最常用、最简洁的加速方式——它让多个异步操作并行发起,而不是串行等待,大幅减少总耗时。
核心写法:直接 await Promise.all([...promises])
把所有请求包装成 Promise 数组,传给 Promise.all,再用 await 等待全部完成:
const fetchUser = () => fetch('/api/user').then(r => r.json());
const fetchPosts = () => fetch('/api/posts').then(r => r.json());
const fetchProfile = () => fetch('/api/profile').then(r => r.json());
// ✅ 并发执行,3 个请求同时发出
const [user, posts, profile] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchProfile()
]);
注意:Promise.all 返回的是一个 Promise,所以必须 await(或 .then),解构赋值才能拿到结果。
错误处理:用 try/catch 捕获任一失败
Promise.all 是“全成功才成功”,只要有一个 rejected,整个就失败。所以务必包裹 try/catch:
- 失败时,
catch拿到的是第一个被 reject 的错误(不是所有错误) - 如果需要容错(比如某个接口挂了也不影响其他),改用
Promise.allSettled
try {
const [user, posts, profile] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchProfile()
]);
console.log({ user, posts, profile });
} catch (err) {
console.error('某个请求失败了:', err.message);
}
动态请求列表:先构造 Promise 数组再 await
当请求 URL 或参数来自数组(如批量查用户 ID),别在循环里 await —— 那是串行!正确做法是先 map 出 Promise 数组:
const userIds = [1, 2, 3, 4, 5];
// ❌ 错误:for 循环 + await → 串行执行
// for (const id of userIds) { await fetch(`/api/user/${id}`); }
// ✅ 正确:map 出 Promise 数组,再 Promise.all
const userPromises = userIds.map(id =>
fetch(`/api/user/${id}`).then(r => r.json())
);
const users = await Promise.all(userPromises); // 5 个请求并发
限制并发数量(防请求爆炸)
如果要请求几百个,Promise.all 会一次性发出去,可能触发浏览器限流或服务端拒绝。此时需节流,例如用 p-limit 库或手写分批:
- 简单分批:把大数组切成每批 6 个,逐批
Promise.all - 推荐库:
npm install p-limit,然后limit(...promises)
import pLimit from 'p-limit'; const limit = pLimit(6); // 同时最多 6 个 const promises = urls.map(url => limit(() => fetch(url).then(r => r.json()))); const results = await Promise.all(promises);
不复杂但容易忽略:并发 ≠ 无脑 all,关键在 Promise 数组是否真正并行创建,以及错误是否合理兜底。











