I am trying to use a joke API and Rest country API. I made 2 async functions, but when I use the country API I need to click the submit button twice before the country flag and coat of arms images loads. The joke api retrieves the data right away.
app.post("/", urlEncodedParser, (req, res) => {
sendJokeRequest();
let countryName = req.body.country;
console.log(countryName);
sendCountryRequest(countryName);
res.render("api-page", {
data: req.body.country,
joke: joke,
countryFlag: countryFlag,
countryCoatOfArms: countryCoatOfArms
});
});
var joke;
var countryFlag, countryCoatOfArms
const sendJokeRequest = async () => {
try {
const response = await axios.get("https://api.chucknorris.io/jokes/random");
console.log(response.data.value)
joke = response.data.value;
} catch (err) {
console.error(err);
}
};
const sendCountryRequest = async (country) => {
try {
const response = await axios.get(`https://restcountries.com/v3.1/name/${country}?fullText=true`);
console.log(response.data[0]);
countryFlag = response.data[0].flags.svg;
countryCoatOfArms = response.data[0].coatOfArms.svg;
} catch(err) {
console.error(err);
}
}
CodePudding user response:
since sendJokeRequest
and sendCountryRequest
are async
you are executing res.render(...
before they have retrieved any data at all - and using "globals" for joke
, countryFlag
and countryCoatOfArms
is a very poor design - they should be returned from sendJokeRequest
and sendCountryRequest
This should work
app.post("/", urlEncodedParser, async (req, res) => {
try {
const joke = await sendJokeRequest();
const countryName = req.body.country;
console.log(countryName);
const {countryFlag, countryCoatOfArms} = await sendCountryRequest(countryName);
res.render("api-page", {
data: req.body.country,
joke,
countryFlag,
countryCoatOfArms
});
} catch(err) {
// handle errors here in one place
}
});
const sendJokeRequest = async() => {
const response = await axios.get("https://api.chucknorris.io/jokes/random");
console.log(response.data.value)
return response.data.value;
};
const sendCountryRequest = async(country) => {
const response = await axios.get(`https://restcountries.com/v3.1/name/${country}?fullText=true`);
console.log(response.data[0]);
countryFlag = response.data[0].flags.svg;
countryCoatOfArms = response.data[0].coatOfArms.svg;
return {countryFlag, countryCoatOfArms};
}