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"
}
});