axios多并发请求

  

场景:

  点击导出Excel按钮实现,姓名列表中前五个的所有的文章数据发送给后端,姓名列表中点击过的数据会被存放到localStorage中;

思路:

  点击导出按钮,把前五个数据逐个和localStorage中的数据对比,找到前五个中没有发送请求的数据,放到数组中,然后对这些没有请求的数据进行一次多并发请求,把多并发请求到的数据存储到浏览器中,再统一按照前五名的姓名顺序到localStorage中拉取数据,提交后台;

问题:

  如何一次发送多个请求?

解决办法:

  方法一:

  

getNameData(name,affiliation){
    return this.$axios.get("/api/academic/paper_search", {
          params: {
             name: name,
             affiliation: affiliation
          }
       })
    },
 sendAllAxios(){
       let arr = []
       this.getFiveNameData.forEach(item => {
       if(!JSON.parse(localStorage.getItem("baseInfo"))[item.name]){
           arr.push( this.getNameData(item.name,item.affiliation))
          }
        });
       return new Promise((resolve,reject)=>{
            if(arr.length){
                this.$axios.all(arr).then((res)=>{
                res.forEach(item=>{
                   if(item.status == 200){
                       this.baseInfo[item.config.params.name] = item.data
                    }
                     })
                localStorage.setItem("baseInfo",JSON.stringify(this.baseInfo))                            
                resolve()
            }).catch(e=>{console.log(e)})
         }else{
            let sendData = {}
            this.getFiveNameData.forEach(item => {
            sendData[item.name] = JSON.parse(localStorage.getItem("baseInfo"))[item.name]
          })
             resolve(sendData)
         }
       })     
     },
            

方法二:

  Promise.all(arr).then(res=>{ })

踩坑:

 this.$axios.all(arr).then((res)=>{})中then的第一个参数是一个数组,表示所有请求的信息;

 this.$axios.all(arr).then(this.$axios.spread(function (acct, perms){ }) 这种方式是请求返回的数据形式的数据逐个展开,acct表示请求返回后数组中的第一条数据,perms表示第二条数据,

注意:

  spread是在确定几个请求一起发的情况下用

 

猜你喜欢

转载自www.cnblogs.com/zmdblog/p/11240226.html