Javascript async function console log the returned data Javascript async function console log the returned data json json

Javascript async function console log the returned data


Two issues:

  1. To set the resolution value of the promise created by the async function, you have to use a return statement from the async function itself. Your code has a return in the getJSON callback (which is ignored), not the async function itself.

  2. To get the resolution value of an async function, you must await it (or consume its promise in the older way, via then, etc.).

For #1, you could return the result of awaiting getJSON:

async function getData() {    try {        return await $.getJSON('./data.json').promise();    }    catch (error) {        console.log("error" + error);    }    finally {        console.log('done');    }}

And for #2, you'd need to either await your function (this would, in turn, need to be inside an asyncfunction):

console.log(await getData());

...or consume its promise via then:

getData().then(data => {    console.log(data);});

Side note: Your getData hides errors, turning them into resolutions with the value undefined, which is generally not a good idea. Instead, ensure that it propagates the error:

catch (error) {    console.log("error" + error);    throw error;}

Then, naturally, ensure that anything using getData either handles or propagates the error, making sure something somewhere does handle it (otherwise, you get an "unhandled rejection" error).


Re your comment

how would I access the "stuff" in the json file from the log outside the function?

The async result / resolution value of getData is the object the JSON defined (it's no longer JSON, it's been parsed). So you'd use .stuff on it, e.g.:

// In an `async` functionconsole.log((await getData()).stuff);// Or using `then`:getData().then(data => {    console.log(data.stuff);});