How can I call an async function inside a jQuery .change function? I have tried the following and it returns me "undefined"...
async function getData(){
try {
return await $.getJSON('./data.json').promise();
} catch(error) {
console.log("error" + error);
throw error;
} finally {
alert("done");
}
}
Here an example of the JSON:
{
"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"]
}
}
}
}
And Here is the jQuery function:
$('select[name="make"]').change(function(){
// THIS LET RETURNS EITHER First or Second
let makeSelected = $('select[name="make"] option:selected').val();
getData().then(data => {
let topModels = data.stuff;
// THIS RETURNS UNDEFINED
console.log(topModels.makeSelected);
// THIS RETURNS THE CORRECT DATA
console.log(topModels.First);
});
});
How come the let variable does not work for the first console.log?