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是在確定幾個請求一起發的情況下用

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM