我正在尝试基于post-ids 数组递归执行axios.get((请求
let returnArray = []
post_ids = [0,1,2,3,4,5]
for (const id of post_ids) {
axios.get('api/events/' + id)
.then(response => returnArray = returnArray.concat(response.data))
.catch(error => {
console.log('Event not found: ', error)
return returnArray
})
}
return returnArray
我知道其中一个post-id将是无效的,并且将从API返回代码404。
我遇到的问题是返回数组是空的,而不是所有有效post-id查询的JSON数据(减去无效查询(
有什么想法吗?
感谢
如果您希望这实际上是递归的,您需要一个函数,您可以在.then
内部递归调用它。但这会使事情变得比需要的更复杂。在循环中只调用await
如何?
const returnArray = [];
const post_ids = [0,1,2,3,4,5];
for (const id of post_ids) {
try {
returnArray.push(await axios.get('api/events/' + id));
} catch(e) {
console.log('Event not found: ', id)
}
}
return returnArray;