我有以下代码:
var pagina
var array_de_urls=[]
for (pagina=1; pagina <= self.state.numero_de_paginas; pagina++) {
array_de_urls.push(Constantes.URL_PREFIX + '/courses/'+course_id+'/enrollments?role[]=StudentEnrollment&state[]=active&per_page='+Constantes.PER_PAGE_VALUE+'&page='+pagina)
}
代码运行后,“ array_de_urls”参数中包含13个URL。
然后我运行这段代码
array_de_urls.forEach(url => {
axios.get( url, config
).then((response) => {
console.log("getAlunosArray chamado axios")
var joined = self.state.array_aluno.concat(response.data);
self.setState({ array_aluno: joined })
}).catch((error) => {
console.log("error array_de_urls: "+error)
});
});
我能够将所有结果串联在“ array_aluno”状态参数中。
但是现在我想尝试另一种方法。
我想创建一个异步函数,该函数不使用“状态”参数就返回值。
我尝试运行以下代码:
var pagina
var array_de_urls=[]
for (pagina=1; pagina <= self.state.numero_de_paginas; pagina++) {
array_de_urls.push(Constantes.URL_PREFIX + '/courses/'+course_id+'/enrollments?role[]=StudentEnrollment&state[]=active&per_page='+Constantes.PER_PAGE_VALUE+'&page='+pagina)
}
let response = []
for (let i = 0; i < array_de_urls.length; i++) {
response.concat( await axios.get( array_de_urls[i], config ) );
}
return response.data
但是我从该代码中得到了一个“未定义”的对象。
我该怎么做呢?
答案 0 :(得分:0)
我能够创建一个函数来解决我的问题。
export async function getAlunoArrayAsync(config, course_id, self) {
console.log("getAlunoArrayAsync chamado")
var pagina
var array_de_urls=[]
for (pagina=1; pagina <= self.state.numero_de_paginas; pagina++) {
array_de_urls.push(Constantes.URL_PREFIX + '/courses/'+course_id+'/enrollments?role[]=StudentEnrollment&state[]=active&per_page='+Constantes.PER_PAGE_VALUE+'&page='+pagina)
}
var merged = [];
await axios.all( array_de_urls.map(l => axios.get(l, config)) )
.then(res => {
merged = [].concat(res)
})
let concatenated = []
for (let i = 0; i < merged.length; i++) {
// console.log("merged merged[i].data")
// console.log(merged[i].data.length)
for (let j = 0; j < merged[i].data.length; j++) {
//console.log("merged merged[i][j].data: "+j)
//console.log(merged[i].data[j])
concatenated.push( merged[i].data[j] )
}
}
return concatenated
}