【发布时间】:2020-06-05 00:32:57
【问题描述】:
我正在编写一条生成多张发票的路线。 我正在使用的中间件从 mysql 数据库中获取数据。 就是先检查custid是否存在,然后获取客户的季度成本,然后生成发票号。 我使用的代码如下:
中间件:
enter code here
const check_exists=async(req,res,next)=>{
var sql='SELECT EXISTS(SELECT 1 FROM customers WHERE id ='
+req.query.custid+') AS ex;'
connection.query(sql, await function(err,result) {
if(err) throw err;
console.log('check_exists=='+result[0].ex)
req.exist=result[0].ex
if(result[0].ex<1){
//res.send('custid '+req.query.custid+' no exist')
res.end()
}//{res.send('custid '+req.query.custid+' no exist')}
else{ next() }
});////connection
}
enter code here
const getQcost=async(req,res,next)=>{
var sql='SELECT quarterly_cost from customers'+
' WHERE id='+req.query.custid+';'
connection.query(sql, await function(err,result) {
if(err) throw err;
req.Qcost=result[0].quarterly_cost;
console.log('quarter_ cost=='+req.Qcost)
next()
});////connection
}
enter code here
const inv_count=async(req,res,next)=>{
var sql='SELECT COUNT(custID) AS inv_count from payments '+
' where (custID='+req.query.custid+' && invoice_no!="");';
connection.query(sql, await function(err,result) {
if(err) throw err;
//console.log('Data saved to payments:\n');
//console.log('the variable result====',JSON.stringify(result));
console.log('inv_count=='+result[0].inv_count)
req.inv_count=result[0].inv_count;
next()
});////connection
}
接电话:
enter code here
router.get('/inv',check_exists, getQcost, inv_count, function(req,res,next){
req.inv=(req.inv_count+1).toString()
req.invoice_no=req.query.custid+'-'+req.inv
var VALUES='('+req.query.custid+', CURDATE(), '+req.Qcost+
' , '+'"for regular cleans in quarter: 12 Apr 20-12 July 20"'+
', '+'"'+req.invoice_no+'"'+')'
res.send(VALUES)
})
它应该运行 check_exists 然后 getQcost 然后 inv_count。 但是,它在调用 3 次时给出的输出如下:
enter code here
check_exists==1
quarter_ cost==23.4
inv_count==1
check_exists==1
check_exists==1
quarter_ cost==23.4
quarter_ cost==23.4
inv_count==1
inv_count==1
我的代码有问题吗? 对于少量的呼叫似乎无关紧要,但遇到麻烦时 调用次数超过200左右。
【问题讨论】:
-
我真的很困惑。你为什么打电话给
await function(err,result) { ... }?在回调函数上调用await会将不应混合的两种模式混合在一起。使用回调或 Promises。