I have a function that involves fetching data via ajax and making a table and returning said table. I also have a function that gets triggered when a button is clicked. I have names this function with async
and hoped that when i called the function to get the table, it would wait for it to finish (I have used await
) then the rest of the code would follow. But instead the console logs the table with no data in it (because it needs time for the data to be fetched), instead console logs the empty table right away.
The trigger function
const exportPdf = async () => { //Called from a button
let tableBody = await getTableBody('v7xn82Ff3XQFYwCl');
console.log(tableBody);
}
The function that returns the table
const getTableBody = async (crop) => {
table = $('#pests_js_table').DataTable({
"pageLength": 50,
"processing": true,
"ajax": {
"url": '/assets/ajax/table_ajax_handler.php',
"type": "POST",
"data": {
action: "getPestsForTable"
}
},
"rowsGroup": [
],
"columns": [{
"data": "crop"
},
{
"data": "pests"
},
{
"data": "chemical"
},
{
"data": "product"
},
{
"data": "rate"
},
{
"data": "max_no"
},
{
"data": "hi"
},
{
"data": "mrl"
},
{
"data": "pcs_no"
},
{
"data": "supplier"
},
{
"data": "use_by_date"
}
],
"columnDefs": [{
"targets": [0],
"visible": false,
"searchable": true
},
{
"targets": [1],
"visible": true,
"searchable": true
}
],
"order": [
[2, "asc"]
],
"rowsGroup": [
1, 2, 4, 5, 6, 7, 9
]
});
let tableBody = $('#pests_js_table').html();
table.destroy();
return tableBody;
}