Axios 類似於for循環發送批量請求{:axios.all axios.spread}。


Axios的請求都是異步的!不能用for循環遍歷去批量發送請求

那如果我們需要類似與這樣的請求怎么辦呢

for(let i =0;i<array.length;i++){
  axios.post(contentPath + 'invoice/new/updatetitle', JSON.stringify(sendTaitol), {
                headers: {
                    "Content-TYpe": "application/json;charset=utf-8"
                }
     });
}

Axios官方也是支持的

主要是:axios.all 方法和 axios.spread方法的運用

let requestArray = new Array();//建立一個存儲需要發送的請求
requestArray.push(this.bingfaSendRequestByPhone());//為請求數組添加具體的請求
requestArray.push(this.bingfaSendRequestByTital());
requestArray.push(this.bingfaSendRequestByTuiSong());
axios.all(requestArray).then(
    axios.spread((...resp) => {//可變 ...擴展運算符將數組變成一個參數序列
        let flagByRequest = true;//標志位初始化定制false
        let flagByRequestIndex = "";//失敗數據
        [...resp].forEach((item, index) => {
            if (!item.data.success) {
                flagByRequest = false;
                flagByRequestIndex += index + ",";
            }
        });
        //如果都是成功的就跳轉
        if (flagByRequest) {
            console.log(flagByRequestIndex);//失敗的請求下標索引
        }

    })
).catch(error => {
    console.log(error)
});

具體的請求數組添加的內容形式如下Demo

 let sendPhone = this.localUpdateDataToDo.SendPhoneData;
            axios.post(contentPath + 'invoice/new/acceptModAcct', sendPhone, {
                headers: {
                    "Content-TYpe": "application/json;charset=utf-8"
                }
            });


免責聲明!

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



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