afshar003
afshar003

Reputation: 839

turning a string to and array then passing to another function by chance javascript

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
}

Upvotes: 0

Views: 62

Answers (1)

tadman
tadman

Reputation: 211560

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.

Upvotes: 1

Related Questions