vue for循环中按顺序执行axios请求

本文介绍如何在Vue3中通过for循环逐个发起axios请求,并利用Promise.all确保按顺序处理响应数据。通过封装axios、存储结果并使用Promise.all解析,实现有序数据获取与后续操作。
摘要由CSDN通过智能技术生成

vue for循环中按顺序执行axios请求
需求:前端利用for循环遍历一个接口获取信息,利用promise可以保证每次接口遍历正常后统一保存返回的数据

正常使用js和ajax组合中用 闭包就可以实现for循环按顺序执行请求地址操作,但是vue中不可以,所以接下来是使用vue3写的demo,大家可以参考参考

1:封装使用promise

 return new Promise(function (resolve,reject){
     axios
           .get(val)
           .then((response) => {
               console.log(response);
               resolve(response);
           })
   }).catch(err=>{
})

2: 把返回结果存入数组

  let data = [];
  for(let i = 0; i < pathList.length; i++){
       let result = getAxios(pathList[i].path);
       data.push(result);
   }

3: 再用Promise.all的方法进行解析

Promise.all(data).then(itemList => {
   console.log(itemList) //itemList返回的数据是按顺序的
     //执行自己接下来的操作
     //doSomething
 })

完整代码:

let pathList = [
         {name: '请求1', path: 'http://xxxxxx1'},
         {name: '请求2', path: 'http://xxxxxx2'},
         {name: '请求3', path: 'http://xxxxxx3'},
         {name: '请求4', path: 'http://xxxxxx4'}
 ]
 const getData = ()=>{
     let data = [];
     for(let i = 0; i < pathList.length; i++){
         let result = getAxios(pathList[i].path);
         data.push(result);
     }

     Promise.all(data).then(itemList => {
         console.log(itemList) //itemList返回的数据是按顺序的
         //执行自己接下来的操作
         //doSomething
     })
 }

 const getAxios = (val)=>{
     return new Promise(function (resolve,reject){
         axios
             .get(val)
             .then((response) => {
                 console.log(response);
                 resolve(response);
             })
     }).catch(err=>{

     })
 }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值