Vue组合式API onMounted中用Promise.all并行发送多API请求优化性能
如何在Vue组合式API的onMounted中并行发送多个请求提升性能
你可以通过Promise.all()实现多个请求的并行发送,替代原来的串行await逻辑,所有请求会同时发起,总耗时等于最慢请求的处理时间,能大幅提升性能。
改造后的基础版本
基于你现有代码的逻辑,直接修改为并行请求写法:
onMounted(async () => { // 提前创建所有请求的Promise实例(此时请求已开始发送) const requestPromises = [ ExApiService.get("exit-city"), ExApiService.get("destination-city"), ExApiService.get("destination-warehouse"), ExApiService.get("expense-detail") ]; // 等待所有请求完成,获取全部结果 const results = await Promise.all(requestPromises); // 逐个处理结果,逻辑和原代码完全一致 const [error, res] = results[0]; if (error) ErrorPopup(error); else exitCityId.value = res.data; const [err, resp] = results[1]; if (err) ErrorPopup(err); else destinationCityId.value = resp.data; const [er, re] = results[2]; if (er) ErrorPopup(er); else destinationWarehouseId.value = re.data; const [e, r] = results[3]; if (e) ErrorPopup(e); else expenseDetail.value = r.data; });
优化版(更易维护)
如果后续需要新增或修改请求,可通过配置映射简化代码,避免重复判断逻辑:
onMounted(async () => { // 定义请求配置:接口路径 + 成功后要赋值的响应式变量 const requestConfigs = [ { path: "exit-city", target: exitCityId }, { path: "destination-city", target: destinationCityId }, { path: "destination-warehouse", target: destinationWarehouseId }, { path: "expense-detail", target: expenseDetail } ]; // 并行发起所有请求 const results = await Promise.all( requestConfigs.map(config => ExApiService.get(config.path)) ); // 批量处理结果 results.forEach(([error, res], index) => { if (error) { ErrorPopup(error); } else { requestConfigs[index].target.value = res.data; } }); });
注意事项
- 如果
ExApiService.get在请求失败时会抛出错误(返回rejected状态的Promise),需要给每个请求添加catch处理,确保Promise.all能正常接收所有结果:const requestPromises = requestConfigs.map(config => ExApiService.get(config.path) .catch(err => [err, null]) // 将错误转换为[error, null]结构,和原逻辑对齐 ); - 并行请求不会互相阻塞,所有请求同时发送,能有效减少页面加载的等待时长。
内容的提问来源于stack exchange,提问作者kadirklc
相关产品推荐
相关产品推荐

