首页 > 解决方案 > 使用 Sequelize 在 NodeJS 中实现异步的问题

问题描述

我有一个 API 将接受如下请求正文的场景,但我未能实现异步操作。场景是 API 应该只接受未提交超过已存储在数据库中的现有余额的特定项目的支付金额。

{
    "items": [
        {
            "itemId": "3c6d9287-a247-4852-b168-29f766e073fb",
            "paidAmount": 5
        },
        {
            "itemId": "8f3ebe13-b4dd-4b5c-887c-9663b29065cd",
            "paidAmount": 5.80
        }
    ]
}

预期的执行流程将是:

  1. 将正文请求与数据库中的现有数据进行比较。
  2. 执行体请求的减法未完成Blc(由sequelize 函数处理)和payamount。
  3. 如果减法值小于 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});
}

标签: node.jsasynchronous

解决方案


最后 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
    });
}
})

推荐阅读