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

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=>{
    
    

     })
 }

猜你喜欢

转载自blog.csdn.net/qq_37656005/article/details/121947076