Why is my variable not Global ?
I have successfully fetched data from an API, and can console.log it in one function but not another. How do I make it globally accessible please?
10 Replies
It is global, it's just not working like you think it does. The top level of javascript isn't going to wait for getMovies to finish running before moving on
https://codepen.io/jochemm/pen/vYMWmww?editors=1011
take a look at the order of the console logs in that pen
you'll see that it calls getmovies, then immediately moves on to calling displaycurrentmovie before getmovies has time to finish / set the movieList to a testing value, then much later it logs out 'after await'
to be more precise, it runs the synchronous part of the function, then the async part runs whenever the async part is ready to be run
async/await is just syntactic sugar, it doesn't work fundamentally differently than using
.then()
ahhhhh, thank you, i understand that. so how do i get the displayCurrentMovie() to wait also ?
easiest way I see is to just call it in getMovies()
i guess, but i will need this info later and other functions will need the data, how to i prevent them being called before the api has loaded the data
generally, you'd have this in a loading function that blocks the UI until the loading is done. Something with a spinner. That way, you're in control of whether other functions are triggered or not
i thought that was the whole point of async / await
is there a simple way of loading the API data and making everything else wait ?
like I said, under the hood it doesn't work any different than using promises with .then
i'm new to APIs
not really, but then you should show a loading state to the user anyway
ok, i shall do some more research, but thanks for clearing up my misunderstanding