I want to rewrite the below code using async await. The problem is while using the below code how should I return the nextInvoiceNo. as a response to my request using callbacks, because the nextInvoiceNo. value is getting lost outside the braces. And please help me to write the code using async await.
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password : '',
database : 'data2020'
});
app.get('/nextInvoiceNumber',(req,res)=>{
let shopName = "KR";
let counterName = "F";
let nextInvoiceNo = 1;
shopName = shopName.trim();
counterName = counterName.trim();
//get shop id
let st = getStoreByName(shopName,(err,result)=>{
if(err){
console.log(err);
}else{
if(result.length>0){
result.forEach(element=>{
storeId = element['id'];
});
let sql = "Select * from store_sale where store_id = '"+storeId+"' and counter_name = '"+counterName+"' and is_delete <> '1' ORDER BY invoice_no DESC LIMIT 0,1";
let t = db.query(sql,(err,res)=>{
if(err){
console.log(err);
}
else{
if(res.length>0){
res.forEach(element=>{
nextInvoiceNo = element['invoice_no']+1;
});
}
else{
console.log("No Sales Found");
}
}
});
}
else{
console.log("Invalid StoreName")
}
}
});
res.send("done");
})
function getStoreByName(shopName,callback)
{
name=shopName.trim();
sql = "Select id,name from store_master where name = '"+name+"' AND is_delete <> '1' LIMIT 0,1"
let t = db.query(sql,(err,result)=>{
if(err){
callback(err,null);
}
else{
callback(null,result);
}
});
}