0

i made a fetch request (i turned a text into array)and i want them to pass each array element by accident in another function.

function randomSingleWord() {
    fetch('http://www.randomtext.me/api/').then(res => res.json() )
    .then(data => data.text_out.split(' ');
    return data //random or by order single word
}
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
afshar003
  • 765
  • 6
  • 6
  • It's 2020, we have `await` now. That would help trim down how much code you have to write. – tadman Sep 12 '20 at 22:36
  • 1
    Is this asking "How do I shuffle an array in JavaScript?" or "How do I pick a random element from a JavaScript array?" – tadman Sep 12 '20 at 22:36
  • yes i am asking this questions."How do I shuffle an array in JavaScript?" or "How do I pick a random element from a JavaScript array?" – afshar003 Sep 12 '20 at 22:38
  • Does this answer your question? [Get a random item from a JavaScript array](https://stackoverflow.com/questions/5915096/get-a-random-item-from-a-javascript-array) – tadman Sep 12 '20 at 22:39
  • 2
    Because `fetch` is asynchronous, this `return data` is meaningless. That is, this random word function will always return undefined. I think first you need to return the result of `fetch` (on the first line ```return fetch(...```. The caller will then have a promise which it can use like ```randomSingleWord.then((arrayOfWords) => { })``` and that function can do whatever it wants with the `arrayOfWords`. – mr rogers Sep 12 '20 at 22:39

1 Answers1

1

This has some asynchronous problems that await can fix:

async function randomSingleWord() {
  let data = await fetch('http://www.randomtext.me/api/');

  let words = data.text_out.split(' ');

  return words[Math.floor(Math.random() * words.length)];
}

Where this is now a Promise, so then or await applies.

tadman
  • 208,517
  • 23
  • 234
  • 262