I'm here because I don'0t understand how to wait for an SQL response, do some computation, and then send it back to the client using the http POST method. In particular, I want to query a report week by week, aggregate the response in an array and, after it finishes, send the aggregated response to the client using the HTTP post method. Here is the code example:
app.post("/getDataByWeek", (req, res) => {
async function queryDB(){
let dataArray = [];
var today = new Date();
for(let i=0;i<=req.body.prev_week;i++){
let currWeek = today;
currWeek.setDate(currWeek.getDate() - i*7);
dataArray.push(currWeek.toLocaleString().split(" ")[0].replace(",",""))
}
let scarti = [];
let prod = [];
let dateArray = [];
let pool = await sql.connect(configSQL);
let data = pool.request()
for(var i=dataArray.length - 1;i>0;i--){
let startDate = normData(dataArray[i]);
let endDate = normData(dataArray[i-1]);
let query_string = "SELECT SUM(qty_good) as PRODOTTE, SUM(qty_reject) as SCARTO FROM [MESDB].[dbo].[vw_oee_data] where ent_name = 'Scatolatrice' and cast(hour_end_local as time) BETWEEN '06:00:00.000' AND '21:00:00.000' and cast(hour_end_local as date) BETWEEN '" + startDate +"' AND '" + endDate + "'";
await data.query(query_string, function (err, recordset) {
prod.push(recordset.recordset[0].PRODOTTE)
scarti.push(recordset.recordset[0].SCARTO)
dateArray.push(endDate)
})
}
return prod,scarti,dateArray;
}
queryDB().then((prod,scarti,dateArray)=>console.log(prod))
});
At the end of the code I simply used console.log() to print the results, but they are empty. Could you please help me to understand how I have to wait for SQL response before continuing the code execution?
I have tried the code above, but the result (for example the prod array) is empty.