node.js - 使用 Sequelize 在 NodeJS 中实现异步的问题
问题描述
我有一个 API 将接受如下请求正文的场景,但我未能实现异步操作。场景是 API 应该只接受未提交超过已存储在数据库中的现有余额的特定项目的支付金额。
{
"items": [
{
"itemId": "3c6d9287-a247-4852-b168-29f766e073fb",
"paidAmount": 5
},
{
"itemId": "8f3ebe13-b4dd-4b5c-887c-9663b29065cd",
"paidAmount": 5.80
}
]
}
预期的执行流程将是:
- 将正文请求与数据库中的现有数据进行比较。
- 执行体请求的减法未完成Blc(由sequelize 函数处理)和payamount。
- 如果减法值小于 0,则 API 应将错误消息返回给调用者。否则,它将继续执行后续循环。
在循环内的一系列执行之后,我遇到了捕获 allAccepted 变量的最终值(显示在下面代码的最后 3 行)的任何问题。
var data = req.body;
var items = data.items;
var total = items.map(itm =>{ return itm.paidAmount; }).reduce((a, b) => a + b, 0).toFixed(2);
var blc = 0.00;
const balance = await checkBalance(req,res);
if (balance != null){
blc = balance;
}
if (blc < total){
return res.status(403).json({error:"Insufficient balance to complete the payment!"});
}
var allAccepted = false;
Promise.all(items.map(v=>{
OrderItemTransaction.findOne({
where:{itemId:v.itemId},
attributes: [
[db.Sequelize.literal('(OrderItem.unitPrice - SUM(paidAmount))'), 'outstandingBlc']
],
include:[{
model: OrderItem,
on: {
'id': { [Op.eq]: db.sequelize.col('OrderItemTransaction.itemId') }
},
required: true
}],
raw:true
}).then(itemInfo=>{
if (!itemInfo){
return void res.status(404).json({error:"Invalid item Id"});
}
else{
const reqPaidAmount = v.paidAmount;
const outstandingBalance = itemInfo.outstandingBlc;
console.log(reqPaidAmount +"|" + outstandingBalance);
if (outstandingBalance - reqPaidAmount < 0){
allAccepted = false;
return res.status(403).json({error:`Cannot complete payment for ${v.itemId} because paid amount is ${reqPaidAmount} and outstanding balance is ${outstandingBalance}`})
}
else{
allAccepted = true;
}
}
}).catch(err=>{
console.log(err);
return res.status(500).json({error:err.message});
});
}));
console.log(allAccepted);
if (allAccepted == true){
return res.status(200).json({total:total,blc:blc});
}
解决方案
最后 3 行代码不会等到 promise.all 执行后添加 then 块,如下所示。
Promise.all(
items.map(v => {
// your db operations code
})
).then(promiseAllResult => {
if (allAccepted == true) {
return res.status(200).json({
total: total,
blc: blc
});
}
})
推荐阅读
- python - Python:如何每次获取数组的下 k 个连续元素?
- visual-studio-2015 - 未生成 CMake 目标 RUN_TESTS
- android - 我有一个始终以固定大小显示的 TextView
- google-data-studio - 如何添加动态过滤数据的下拉控件?
- amazon-web-services - Terraform:如何在 concat 变量后添加子网掩码?
- c - 如何从文件中获取全名并将其与用户搜索的内容进行比较?
- python-3.x - 如何在处理其他代码时让 python 等待?
- oracle-apex - 用于将所选记录的列值更新为 sysdate 的按钮
- netsuite - 项目履行搜索工具包/包裹项目
- node.js - Node.js 有没有办法将时间戳转换为 .csv 文件中的日期?