0

Not the brightest with async JS yet but after trying many different variations after many google searches and getting nowhere thought I'd finally ask for some help. (My way of saying please be easy on me for what is probably a dumb question)

What I'm trying to do is get the data object and store it to be used elsewhere in the code. Below is the latest thing I tried and am getting a result of undefined from the console.log().

 let apiData;

            const getData = async () => {
                const response = await fetch('myapirurl');
                const data = await response.json();
                return data;
            }
            
            getData().then(result => {
                apiData = result;
            })

            console.log(apiData);
  • You can store it like that, but you won't be able to log it immediately, since `console.log()` runs before the async function has completed. But you should be able to use it later, for instance in an event listener. – Barmar Jul 22 '22 at 20:12
  • 1
    All the code that needs `result` (or `apiData`) should be *inside* that callback, or called from there. Remember that the callback is called *later*. – trincot Jul 22 '22 at 20:13

0 Answers0