Reputation: 33
I am trying to recursively perform an axios.get() request based on an array of post ids
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
I know that one of these post ids will be invalid and will return a code 404 from the API.
The problem I am having is that the return array is empty, rather than JSON data of all the valid post id queries (minus the invalid one)
Any ideas?
Thanks
Upvotes: 0
Views: 227
Reputation: 371019
If you want this to be actually recursive, you need a function that you can call recursively inside the .then
. But that makes things more complicated than they need to be. How about just await
ing each call inside the loop?
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;
Upvotes: 1