Javascript async function console log the returned data
Two issues:
To set the resolution value of the promise created by the
async
function, you have to use areturn
statement from theasync
function itself. Your code has areturn
in thegetJSON
callback (which is ignored), not theasync
function itself.To get the resolution value of an
async
function, you mustawait
it (or consume its promise in the older way, viathen
, etc.).
For #1, you could return the result of await
ing 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 async
function):
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);});