vue 3 中 axios 并发请求合并数据的核心是 promise.all,需全部成功才执行 then;失败则进入 catch;可用 promise.allsettled 实现容错降级,按状态分别处理响应。

Vue 3 中 Axios 处理多个并发请求并确保全部成功后再合并数据,核心是用 Promise.all 包裹多个 axios 请求,并在 .then() 中解构响应、统一赋值。关键在于:所有请求必须都 resolve,否则整个 Promise 链会进入 catch;数据合并靠手动拼接或映射,不依赖框架自动处理。
用 Promise.all 并行发起请求并合并结果
这是最常用、最直接的方式。每个 axios 调用返回 Promise,Promise.all 等待全部完成,再按顺序返回响应数组:
- 定义多个独立请求函数(推荐封装,便于复用和测试)
- 传入 Promise.all 的数组中,顺序即后续解构顺序
- 在 then 回调里用数组索引或结构赋值提取 data,再合并到响应式对象中
示例(Composition API):
import { ref, onMounted } from 'vue'import axios from 'axios'
export default {
setup() {
const userInfo = ref(null)
const productList = ref([])
const categories = ref([])
const loading = ref(false)
const fetchAllData = async () => {
loading.value = true
try {
const [userRes, goodsRes, cateRes] = await Promise.all([
axios.get('/api/user/profile'),
axios.get('/api/products?limit=10'),
axios.get('/api/categories')
])
// 全部成功,分别赋值
userInfo.value = userRes.data
productList.value = goodsRes.data.list || []
categories.value = cateRes.data.items || []
} catch (err) {
console.error('某一个请求失败,全部数据未加载', err)
} finally {
loading.value = false
}
}
onMounted(fetchAllData)
return {
userInfo,
productList,
categories,
loading
}
}
}
用 axios.all + axios.spread(兼容旧写法,Vue 3 中仍可用)
axios.all 是 Axios 自带的 Promise.all 封装,配合 axios.spread 可让响应参数更语义化,避免数组下标硬编码:
- 适合对响应顺序敏感、且希望形参名明确的场景(如
(userRes, postRes) => {}) - 注意:axios.spread 在较新版本中已标记为 deprecated,但功能正常;建议优先用解构赋值替代
简写示例:
axios.all([axios.get('/api/user'),
axios.get('/api/posts')
]).then(axios.spread((userRes, postRes) => {
userInfo.value = userRes.data
postList.value = postRes.data
}))
合并数据的常见方式(不只是简单赋值)
“合并”不等于逐个赋值,实际业务中常需结构整合:
-
组合成新对象:比如把用户信息 + 首页 banner + 推荐商品组装成
pageData -
扁平化数组:如同时拉取多个分类下的商品,用
[...res1.data, ...res2.data]合并 - 映射关联字段:例如商品列表返回 category_id,分类数据已加载,可做本地关联(避免额外请求)
-
状态标记:用
isAllLoaded: true控制骨架屏或错误提示的显示逻辑
失败时如何优雅降级(非完全丢弃)
Promise.all 一失败全失败,但你可以用 Promise.allSettled 改进容错性:
- 它不会因某个请求失败而中断,而是返回每个 Promise 的完整状态(fulfilled/rejected)
- 适合“尽力而为”的场景,比如主数据必须加载,辅助数据失败也不阻塞页面
示例片段:
const results = await Promise.allSettled([axios.get('/api/user'),
axios.get('/api/stats'),
axios.get('/api/ads')
])
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
switch (index) {
case 0: userInfo.value = result.value.data; break
case 1: stats.value = result.value.data; break
}
} else {
console.warn(`第 ${index + 1} 个请求失败:`, result.reason)
}
})
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










