promise.all适用于并发执行多个互不依赖的异步请求,需全成功才返回结果;若需容错可用safepromise包装或改用promise.allsettled获取各请求状态。

用 Promise.all() 并发执行多个互不依赖的异步请求,是最常用也最优雅的方式。
用 Promise.all 同时发起所有请求
当几个请求彼此无关(比如同时获取用户信息、商品列表、公告数据),不需要等前一个完成再发下一个,就该让它们并行跑,节省总耗时。
直接把多个 async 函数调用或 fetch 等 Promise 包进 Promise.all([]) 即可:
async function loadData() {
try {
const [user, products, notices] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/products').then(r => r.json()),
fetch('/api/notices').then(r => r.json())
]);
return { user, products, notices };
} catch (error) {
console.error('某个请求失败了', error);
throw error;
}
}
注意 Promise.all 的“全成功”特性
Promise.all 会等待所有 Promise 都 fulfilled 才返回结果;只要有一个 rejected,整个就立刻 reject,不会等其余完成。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
如果某一个请求失败不能影响其他数据的获取,可以提前包装成“永不失效”的 Promise:
- 用
.catch(() => null)或自定义兜底值 - 封装一个安全的辅助函数,比如
safePromise(promise, fallback = null)
const safePromise = (promise, fallback = null) =>
promise.catch(() => fallback);
// 使用示例
const [user, products, notices] = await Promise.all([
safePromise(fetch('/api/user').then(r => r.json()), {}),
safePromise(fetch('/api/products').then(r => r.json()), []),
safePromise(fetch('/api/notices').then(r => r.json()), [])
]);
需要区分成功/失败时,用 Promise.allSettled
如果必须知道每个请求是 fulfilled 还是 rejected,且不想中断流程,就换用 Promise.allSettled():
- 它总是等待全部 Promise 结束(无论成功失败)
- 返回一个对象数组,每个对象含
status("fulfilled" 或 "rejected")和对应value或reason
const results = await Promise.allSettled([
fetch('/api/user').then(r => r.json()),
fetch('/api/products').then(r => r.json()),
fetch('/api/notices').then(r => r.json())
]);
const user = results[0].status === 'fulfilled' ? results[0].value : null;
const products = results[1].status === 'fulfilled' ? results[1].value : [];
const notices = results[2].status === 'fulfilled' ? results[2].value : [];
避免常见误区
别在 Promise.all 里传已经 await 过的值 —— 那就变成串行了:
- ❌ 错误写法:
await Promise.all([await fetch(...), await fetch(...)]) - ✅ 正确写法:
await Promise.all([fetch(...), fetch(...)])
也别忘了错误边界:即使用了 Promise.allSettled,网络异常、JSON 解析失败这些仍可能抛错,建议在每个 fetch 后加 .catch 或用 try/catch 包裹解析逻辑。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










