Reputation: 145
I'm trying to make GET request to a free API and return an array of all French departments as a result. Initially, I was getting empty result, which then I understood I wasn't wait for GET request to end. So I used the promise.all to make sure it waited but it doesn't work, I still get errors and undefined result. This is the code:
make array of departments:
const axios = require('axios')
let postalCode_all = []
for(let i = 1; i < 97; i++) {
if(i < 10){
postalCode_all.push("0" + i)
} else {
postalCode_all.push(i)
}
}
Prepare the GET request to API:
let departements = [];
async function use_api(dep) {
try {
const response = await axios.get("https://geo.api.gouv.fr/departements/" + dep + "?fields=region");
departements.push(response);
} catch (err) {
console.error(err);
}
};
Make the GET request on all of the array firstly made:
(async () => {
const result = await Promise.all(
postalCode_all.map(element => {
return use_api(element);
})
)
console.log(result)
})()
Edit: Errors (404) probably comes from departments like number 20 that doesn't exist, so I think my real issue is array of undefined, I will think about it.
Upvotes: 0
Views: 219
Reputation: 91
I've just tried running your code and I found a couple of issues but I think I've got it working. The first problem is here:
const response = await axios.get("https://geo.api.gouv.fr/departements/" + dep + "?fields=region");
departements.push(response);
Here, response
is the whole HTTP request object - I presume you're only interested in the actual data, not the headers, so we should do this instead:
departements.push(response.data);
Secondly, in the use_api()
function, you are only pushing the data to departements
and then not using this array to print them.
To see the results with your current code, instead of
console.log(result)
you need to do
console.log(departements)
and use that array.
Upvotes: 2