1

I am trying to fetch data from an API, and I have a function that fetches the data, and another function that sets a global variable to the return value of the fetch function and logs it to the console. This works as I use async functions and await. However, after calling the function which sets the global variable and then I try to access that global variable outside of the function, it returns undefined, and also before the console.log() inside the function. I understand that javascript is asynchronous and is is not all sequential, but how do I fix this in my code?

//testurl declared above
let data;

async function fetchData() {
    try {
        const response = await fetch(testUrl);
        const json = await response.json();
        const arr = await json.results;
        return arr;
    } catch (error) {
        console.error(error);
    }

}
async function setData() {
    data = await fetchData();
    console.log(data); //the actual data i want
}

setData();

console.log(data); //undefined
Alex N
  • 23
  • 3
  • 3
    The call to setData is asynchronous, so you need to await it as well. `await setData()` (Top-level await isn't standard, so you'll need to put that in an async function as well). – Marc Baumbach Sep 07 '20 at 16:43

0 Answers0