0

How would I go about accessing the fetched data from a fetch() function without being returned a Promise {<pending>}?

function GetWords() {
    fetch("https://random-word-api.herokuapp.com/word?number=100")
    .then(response => response.json()).then((word => {
    return word
 }));
}

async function LoadWords() {
    const words = await GetWords()
    return words
}

words = LoadWords()

console.log(words);

console.log(words) returns a Promise {<pending>} instead of the actual data which is expected to be an array of words

Expected output example:

['regelated', 'pneumatophores', 'uppers', 'hexachlorethane', 'veloutes', 'hove', 'locomotives', 'vitalist', 'reascending', 'claustrophobias']

What can I change to have such output?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Amir Adel
  • 23
  • 3
  • 1
    You can never get the data out of an async function, once it's a promise; it'll always be a promise... and could access it's data by using async/await inside of a function. – Adnane Ar Jun 12 '22 at 21:10
  • I want to store the fetched data in some sort of variable so I can use it in later parts of the program, if that's the case then how can I access the fetched data so I am able to use it normally as it if was a normal JS array then? – Amir Adel Jun 12 '22 at 21:18
  • Try to use event handlers, create some custom event handler, and once you get the data that your task requires, you can fire up that event and handle it as a callback function with arguments. Of course you would pass the data as an arguement. – Adnane Ar Jun 12 '22 at 21:21

0 Answers0