How can I console log - or do any thing with the data returned from inside an async function?
example: JS FILE:
async function getData(){
try {
$.getJSON('./data.json', (data) => {
return data;
});
} catch(error) {
console.log("error" + error);
} finally {
console.log('done');
}
}
console.log(getData());
JSON FILE:
{
"stuff": {
"First": {
"FirstA": {
"year": [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
},
"FirstB": {
"year": [2007, 2008, 2009, 2010, 2011, 2012],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
}
},
"Second": {
"SecondA": {
"year": [2002, 2003, 2004, 2005, 2006],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
},
"SecondB": {
"year": [2007, 2008, 2009, 2010, 2011, 2012],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
}
}
}
}
How can I return / get access to all the information in the JSON file and work with it. for example I'd like to take the "First" and "Second" and add them to a div. Same with "FirstA" and "FirstB" and "SecondA" and "SecondB"...and so on.
Right now as it stands, I get Promise {: undefined}
Any help would be greatly appreciated.
---------UPDATE---------
If I run the console log inside the function I then can see the json data, but I need access to the data outside the function.
Serge
"So what?" you probably asked? - This is important part, because console. log() is asynchronous. All asynchronous functions come to Event Table in terms of Event Loop.
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.
To return values from async functions using async-await from function with JavaScript, we return the resolve value of the promise. const getData = async () => { return await axios.
The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.
Two issues:
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.
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 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` function
console.log((await getData()).stuff);
// Or using `then`:
getData().then(data => {
console.log(data.stuff);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With