I'm creating a simple project in JavaScript and can't seem to figure out why this is not working for me. I created a function that fetches an API to get a random country name, and then push that country name in to an empty array, but I can't seem to figure out how to assign value to my variable from that array, probably missing something easy here.
getRandomWord();
getRandomWord();
getRandomWord();
getRandomWord();
const words = [];
let selectedWord = words[Math.floor(Math.random() * words.length)];
console.log(words);
console.log(selectedWord);
// Fetch some random words
async function getRandomWord() {
const res = await fetch('https://randomuser.me/api');
const data = await res.json();
const randomWord = data.results[0].location.country;
words.push(randomWord);
}
I need to assign one random country name from words array to selectedWord but it throws undefined all the time, although I see 4 different country names in words array at locations from 0 to 3. Can someone explain this to me or maybe have even a better approach for this. Thanks !
awaitforgetRandomWordfunction call,await getRandomWord();selectedWord =will execute before your fetch requests can return a value and populate words array