I know that there's many questions and answers about this but I'm new to JavaScript and I'm facing problem with async/ await function. I have two function : getInvoices()
where I have a ajax call to get the needed data, and loadBarChart(data)
that renders a bar chart. For the chart I'm using ApexCharts. So I first call getInvoices()
function to get the data and then I call loadBarChart(data)
passing the data like this:
$(document).ready(function () {
var data = getInvoices();
console.log(data); // data is undefined
loadBarChart(data);
});
The data
is always undefined
probably because the ajax call is not done jet.
Here is getInvoices()
function code:
function getInvoices() {
var url = "@Url.Action("GetInvoiceCustum");
$.ajax({
type: "GET",
dataType: "json",
url: url,
success: function (data) {
return data;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
Following this I changed the code, but at the end I don't know how to pass the data from getInvoices()
to loadBarChart(data);
So far this is what I have :
$(document).ready(function () {
var url = "@Url.Action("GetInvoiceCustum");
var ajax1 = new Promise((resolve, reject) => {
$.ajax({
type: "GET",
url: url,
success: function (data) {
resolve("OK");
result = data;
},
error: function () {
reject(" ERROR");
},
});
});
//At this point how can I acces the result from ajax call, and call the loadBarChart(data)
ajax1.then(values => {
console.log(values)
}, reason => {
console.log("Errors: " + reason)
});
ajax1.then(function (data1) {
var data = data1.result;
console.log(a);
return data1.result;
//loadBarChart(data);
})
});
Doing this how can I access the data that returns getInvoices()
and then call loadBarChart(data)
, or there are other ways to make this posible?