我必须根据一些调用将一些数据保存在数据库中,因此我可以为此使用诺言,但是由于unhandled promise rejection
出现错误,我不知道出了什么问题。
我有一个控制器,首先我要通过运行查询来检查某项,然后检查是否存在行,然后我要检查count如果count为0,则执行一个功能,否则要处理其他功能。
我的控制器
exports.dispenceCashback = function(req, res) {
const phoneNo = req.body.phoneNo
const billAmt = req.body.billAmt
const cashBack = req.body.cashBack
const billNo = req.body.billNo
User.isValidConsumer(phoneNo)
.then(([rows]) => {
if (rows[0]) { // if consumer valid / exist then go forward
console.log(rows)
let consumerName = rows[0].consumername
User.checkRows(phoneNo)
.then(([rows]) => {
console.log(rows[0].count)
if (rows[0].count == 0) { // checking what is the count of row if 0 then executing this code
User.insertIntoDets(phoneNo, billAmt, cashBack, billNo, consumerName, retailerName, retailerId)
User.insertNew(phoneNo, billAmt, cashBack, consumerName)
}
else { //else do this functanility
User.insertIntoDets(phoneNo, billAmt, cashBack, billNo, consumerName, retailerName, retailerId)
User.update(phoneNo, billAmt, cashBack)
}
})
.catch(error => {
console.log(error)
return res.status(404).json({ error: 'Something went wrong' })
})
}
else {
return res.status(404).json({ error: 'Ooooops!!!! invalid consumer' })
}
})
.catch(err => console.log(err));
}
关于上述代码,这是我运行查询的模型类
static isValidConsumer(phoneNo) {
let sql = 'select * from tpconsumer where consphoneno = ?'
return db.execute(sql, [phoneNo]);
}
static checkRows(phoneNo) {
let sql = 'select count(*) as count from cashbackdisp where consphoneno = ?'
return db.execute(sql, [phoneNo]);
}
static insertIntoDets(phoneNo, billAmt, cashBack, billNo, consumerName, retailerName, retailerId) {
console.log(retailerId, retailerName)
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0');
let yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
let sql = 'INSERT INTO cashbackdispdets (consphoneno, consumername, businessid, businessname, billamt, cashbackamt, billno, billdate, billyear)VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?,?)'
return db.execute(sql, [phoneNo, consumerName, retailerId, retailerName, billAmt, cashBack, billNo, today, yyyy, 'Y']);
}
static insertNew(phoneNo, billAmt, cashBack, consumerName) {
let sql = 'INSERT INTO cashbackdisp (consphoneno, consumername, curyearpurchasedamt, curyearcashbackamt) VALUES (?, ?, ?, ?)'
return db.execute(sql, [phoneNo, consumerName, billAmt, cashBack]);
}
static update(phoneNo, billAmt, cashBack) {
let sql = 'UPDATE cashbackdisp SET curyearpurchasedamt = curyearpurchasedamt+ ' + billAmt + ',curyearcashbackamt = curyearcashbackamt + ' + cashBack + ' WHERE consphoneno = ?'
console.log("sql :" + sql)
return db.execute(sql, [phoneNo]);
}
我已在控制器中注释了一些行,我正在做的事情是: