vuefor循环中按顺序执行axios请求需求:前端利用for循环遍历一个接口获取信息,利用promise可以保证每次接口遍历正常后统一保存返回的数据
正常使用js和ajax组合中用闭包就可以实现for循环按顺序执行请求地址操作,但是vue中不可以,所以接下来是使用vue3写的demo,大家可以参考参考
封装使用promise
return new Promise(function (resolve,reject){
axios
.get(val)
.then((response) => {
console.log(response);
resolve(response);
})
}).catch(err=>{
})
:把返回结果存入数组
let data = [];
for(let i = 0; i < pathList.length; i++){
let result = getAxios(pathList[i].path);
data.push(result);
}
再用Promisall的方法进行解析
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=>{
})
}
文章为作者独立观点,不代表 股票程序化软件自动交易接口观点