首页 > 解决方案 > 当 if-else 满足条件时停止执行

问题描述

当条件满足时,我无法停止该函数以继续执行后续逻辑。如下代码所示,如​​果 oustanding Balance substract reqPaidAmount 小于 0,函数应该停止在这个状态,并向调用者响应相应的错误消息,但是代码并没有在这个阶段停止,虽然我使用了 return。

任何人或开发人员都可以建议我在满足给定条件时停止该功能继续执行的最合适方法。

 items.map(async v => {
        try{
            const itemInfo = await OrderItemTransaction.findOne({
                where: { itemId: v.itemId },
                attributes: [
                    [db.Sequelize.literal('(OrderItem.unitPrice - SUM(paidAmount))'), 'outstandingBlc']
                ],
                include: [{
                    model: OrderItem,
                    attributes: ['id', 'unitPrice'],
                    on: {
                        'id': { [Op.eq]: db.sequelize.col('OrderItemTransaction.itemId') }
                    },
                    required: true
                }],
                raw: true
            });
            if (itemInfo['OrderItem.id'] == null) return void res.status(404).json({ error: "Invalid item Id" });
            const reqPaidAmount = v.paidAmount;
            const outstandingBalance = itemInfo.outstandingBlc;
            console.log(reqPaidAmount + "|" + outstandingBalance);
            if (outstandingBalance - reqPaidAmount < 0) {
                console.log("we're here 1");
                res.status(403).json({ error: `Cannot complete payment for ${v.itemId} because paid amount is ${reqPaidAmount} and outstanding balance is ${outstandingBalance}` })
                return;
            }
            else if (outstandingBalance < 0){
                console.log("we're here 2");
                res.status(403).json({error:`${v.itemId} has been paid by others`});
                return;
            }
        }
        catch(err){
            res.status(500).json({ error: err.message });
        }

当我尝试放置时,我不断收到此错误消息

return res.status(403).json({ error: `Cannot complete payment for ${v.itemId} because paid amount is ${reqPaidAmount} and outstanding balance is ${outstandingBalance}` });

(node:15856) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:518:11)
    at ServerResponse.header (C:\Users\jacob\Desktop\restAPI\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\jacob\Desktop\restAPI\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\jacob\Desktop\restAPI\node_modules\express\lib\response.js:267:15)
    at C:\Users\jacob\Desktop\restAPI\controllers\order.js:376:41
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:15856) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI 
flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15856) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

标签: javascriptnode.js

解决方案


Javascript 有时可以容忍这样的事情,但你有没有注意到这一行

res.status(403).json({ 错误: Cannot complete payment for ${v.itemId} because paid amount is ${reqPaidAmount} and outstanding balance is ${outstandingBalance}})

缺少分号?


推荐阅读