0

Why does the console.log(jsonData) within the async function return the json object in the format I want, and the console.log(jsondata) outside the async function return a message saying Promise { < pending> }.

How do I save the JSON file that I fetched, so that I may store it and read it outside of the function?

async function returnData() {
    const response = await fetch(data_url)
    if (!response.ok) {
        const message = 'An error has occured!'
        throw new Error(message);
    }
    const jsonData = await response.json();
    console.log(jsonData)
    return jsonData;
}

const jsondata = returnData();
console.log(jsondata)
jithinkmatthew
  • 890
  • 8
  • 17

2 Answers2

0

returnData is an async function so the return value will be a promise.

You can get the result value by writing:

(async () => {
  console.log(await returnData())
})()

Take a look at this answer: How to return values from async functions using async-await from function?

Fantantonio
  • 377
  • 4
  • 15
0

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.

benhatsor
  • 1,863
  • 6
  • 20