【发布时间】:2020-07-21 05:54:23
【问题描述】:
我有一个调用 /orderRegistration 的“下订单”按钮,它会根据订单更新库存产品数量并将确认的订单发送到电子邮件
const orderStatus = ['Confirmed', 'Not confirmed'];
router.post('/orderRegistration', (req, res) => {
if (req.session.successAuthentication === true &&
req.session.isWorker === false) {
conn.query(`SELECT orders.id,
products.product_id,
products.product_name,
products.product_amount,
order_product.count
FROM orders INNER JOIN order_product
ON orders.id = order_product.order_id INNER JOIN products
ON order_product.product_id = products.product_id
WHERE orders.id IN(
SELECT id
FROM orders
WHERE user_id=${req.session.userId}
AND status = '${orderStatus[1]}')
AND orders.status = '${orderStatus[1]}';`, (err, selProductId) => {
if (err) {throw err;}
if (selProductId.length > 0) {
let dateNow = new Date();
let prepDate = {
day: (dateNow.getDate() < 10) ? `0${dateNow.getDate()}` : dateNow.getDate(),
month: ( dateNow.getMonth() + 1 < 10) ? `0${dateNow.getMonth() + 1}` : dateNow.getMonth() + 1,
year: dateNow.getFullYear(),
hours: (dateNow.getHours() < 10) ? `0${dateNow.getHours()}` : dateNow.getHours(),
minutes: (dateNow.getMinutes() < 10) ? `0${dateNow.getMinutes()}` : dateNow.getMinutes()
};
let orderDate = `${prepDate.day}.${prepDate.month}.${prepDate.year} ${prepDate.hours}:${prepDate.minutes}`;
let productsInOrderHTML = '';
let totalAmount = 0;
for (let i = 0; i < selProductId.length; i++) {
conn.query(`UPDATE products
SET products.product_count_stock = products.product_count_stock - ${selProductId[i].count}
WHERE products.product_id = ${selProductId[i].product_id}`, err => {
if (err) {throw err;}
productsInOrderHTML += `<tr>
<td>
${selProductId[i].product_name}
</td>
<td>
${selProductId[i].count}
</td>
<td>
${selProductId[i].product_amount}
</td>
</tr>`;
totalAmount += selProductId[i].count *
selProductId[i].product_amount;
if(i === selProductId.length - 1) {
console.log('totalAmount: ' + totalAmount);
}
});
}
} else {
res.send('error');
}
});
} else {
res.send('error');
}
});
但由于调用是异步的,有时循环来不及更新所有产品而发生
if(i === selProductId.length - 1) {
console.log('totalAmount: ' + totalAmount);
}
也就是说,有时totalAmount 可能有时间更新所有产品,有时没有,结果表明totalAmount 不等于用户订购产品的成本。
如何重写或重构查询,以免再次发生这种情况
附:对不起英文,我是通过翻译翻译的,因为我会说俄语。我也可能遗漏了一些东西,如有必要,请纠正我
【问题讨论】:
标签: javascript node.js express mysql2