I'm attempting to send a GET request to a free API in order to retrieve an array of all French departments. Initially, I encountered an issue where I was getting an empty result, which I later figured out was due to not waiting for the GET request to finish. I then implemented promise.all to ensure it waits, but even then, I'm still encountering errors and receiving undefined results. Here's the code snippet:
Create an 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)
}
}
Set up the GET request to the 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);
}
};
Send the GET request for all the elements in the previously created array:
(async () => {
const result = await Promise.all(
postalCode_all.map(element => {
return use_api(element);
})
)
console.log(result)
})()
Edit: The errors (404) might be due to departments like number 20 not existing, so it seems like the actual issue stems from an array of undefined elements. I'll need to look into this further.