0

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 !

3
  • you need to have await for getRandomWord function call, await getRandomWord(); Commented May 14, 2020 at 21:09
  • as D. Seah said, selectedWord = will execute before your fetch requests can return a value and populate words array Commented May 14, 2020 at 21:10
  • Hmm, how do i do this? await getRandomWord(); throws a - Uncaught SyntaxError: await is only valid in async function Commented May 15, 2020 at 15:51

2 Answers 2

1

Ok , so i changed code a bit.

async function getRandomWord() {
  try {
    const res = await fetch('https://randomuser.me/api');
    const data = await res.json();

    const randomWord = data.results[0].location.country;

    return randomWord.toUpperCase();

    // words.push(randomWord.toUpperCase());
  } catch (e) {
    console.log(
      'There has been a problem with your fetch operation: ' + e.message
    );
  }
}

And then just called

(async () => {
  selectedWord = await getRandomWord();
  displayWord();
})();

Can't believe i did this :D Thanks.

Sign up to request clarification or add additional context in comments.

2 Comments

You can accept the answer that helped you to finalize this question. The solution you have is the same as the second snippet I gave (except that you only call getRandomWord() once now, which is different than what your question asked and doesn't change the solution I gave), so it makes sense for you to accept my answer as the solution.
I called getRandomWord() once now, because i don't store the result in the array now and assign it right away to selectedWord . And your code assigned value to selectedWord in the same function, but selectedWord is a global variable and i needed it to be assigned globally.
0

The fetches have not resolved and words[] has not been populated when selectedWords = executes. Using Promise.all and then:

const p = Promise.all([
getRandomWord(),
getRandomWord(),
getRandomWord(),
getRandomWord()
]);

const words = [];

p.then(()=>{
const 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);
}

Note: You will want to use Promise.allSettled if you don't want the fail fast behavior, where any failure will cause it to return immediately. Also notice I'm using Promise.all so that it will run the fetches concurrently instead of waiting on them sequentially.

async/await instead of then

(async()=>{
let words = [];

for(var i = 0; i < 4; i++)
  words.push(getRandomWord());
  
words = await Promise.all(words);

const 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;

  return randomWord;
}

4 Comments

Thanks for the reply , now i understand a bit more, but I still struggle with my solution, this is not working because I need selectedwords to be a global variable because I'm accessing it from a function called displayWord , that is taking the word out of selected word variable. Here is the full code - pastebin.com/Sjp6jaFW . Can you help me out , please?
You can just change const selectedWord= to selectedWord=. But you have to make sure that displayWord is called only after selectedWord is populated.
displayWord(); is called as the very last in the whole script.js file you can see in the pastebin, but changing let selectedWord to selectedWord still is not working. Why is it so hard to do this in javascript? :D
All right , i somehow managed this - (async () => { selectedWord = await getRandomWord(); displayWord(); })();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.