In short
You cannot access promise data outside of the async block without stopping the browser entirely.
Read below for workarounds.
But why?
Asynchronous code, or async for short, gives you the ability to run a function (eg. making a server request) without stopping script execution.
This is crucial when dealing with servers and APIs because server requests take time.
You don't want to stop the browser entirely every time you make a request.
This is why asynchronous code exists, to enable you to do other things while a request is pending.
The reason console.log
gave you a pending promise, is because it hasn't finished executing yet.
You cannot access promise data outside of the async block without stopping the browser entirely.
Conclusion / Workarounds
Your best bet is to make a callback function that the async function (eg. fetch
) "calls back" to when it's finished executing. An example of that would be:
fetch(url).then(callBackFunc);
function callBackFunc(data) { // It automatically "feeds" the function with data
// Do something with data
}
You can also use an async
function with await
, as you did.
What this does is it pauses script execution, but only inside the function it is in.
Then you can call a callback function from there:
async function getData() {
var data = await fetch(url);
callBackFunc(data);
}
function callBackFunc(data) {
// Do something with data
}
References
But seriously, give them a look. They will give you a better understanding of how async works, show why it's important and explain why this was all even created.