如何在JS中用Axios实现基于前置请求的多请求调用
解决方案:基于首个请求结果发起并行请求
方法一:使用Promise.all + 链式调用
在第一个请求的then回调中,用Promise.all并行发起另外两个请求,待两个请求都完成后再处理结果赋值:
const order_id = this.$route.params.order_id axios.get(`/api/v1/orders/${order_id}/`) .then(response => { this.order_main_info = response.data // 并行发起两个请求 return Promise.all([ axios.get(`/api/v1/subjects/${this.order_main_info.subject}/`), axios.get(`/api/v1/worktype/${this.order_main_info.worktype}/`) ]) }) .then(([subjectRes, worktypeRes]) => { // 解构两个请求的响应结果 this.order_main_info.subject_name = subjectRes.data.name this.order_main_info.worktype_name = worktypeRes.data.name }) .catch(err => { console.error('请求出错:', err) })
方法二:使用async/await语法
把逻辑放到async函数中(Vue组件中需将方法声明为async):
async fetchOrderData() { try { const order_id = this.$route.params.order_id // 先请求主订单信息 const orderRes = await axios.get(`/api/v1/orders/${order_id}/`) this.order_main_info = orderRes.data // 并行发起两个请求 const [subjectRes, worktypeRes] = await Promise.all([ axios.get(`/api/v1/subjects/${this.order_main_info.subject}/`), axios.get(`/api/v1/worktype/${this.order_main_info.worktype}/`) ]) // 赋值结果 this.order_main_info.subject_name = subjectRes.data.name this.order_main_info.worktype_name = worktypeRes.data.name } catch (err) { console.error('请求出错:', err) } } // 调用方法 this.fetchOrderData()
关键注意点
- 两个依赖请求无先后依赖,用
Promise.all并行发起可减少总耗时 - 响应结果的解构顺序需和请求数组的顺序对应
- 统一用
catch捕获所有请求环节的错误,便于调试
内容的提问来源于stack exchange,提问作者ILYASEM
相关产品推荐
相关产品推荐

