【问题标题】:Express js request continues to process even after return statement即使在 return 语句之后,Express js 请求也会继续处理
【发布时间】:2022-01-11 21:28:59
【问题描述】:

在下面的代码中 sn-p 即使满足第二个 if 条件并返回

return res.status(400).send({message: "This name is already in use. Please enter a new name"});

,代码仍然继续执行,并在数据库中插入数据。

为什么会发生,我怎样才能阻止它继续执行?

db.task(async t => {
            const totalCustomTemplates = await t.manyOrNone(`SELECT * FROM Test WHERE propertyid = $1`, [
                propertyId,
            ]);

            if (totalCustomTemplates.length < 30 ) {

                //Check if the template name is unique and does not exist for the property already
                totalCustomTemplates.forEach(element => {
                    if(element.campaigntemplatename == templateName)
                    {
                        return res.status(400).send({message: "This name is already in use. Please enter a new name"});
                    }                    
                });

                await db.none('INSERT INTO Test(aid, bid, cid) VALUES ($1, $2, $3)',[a, b, c]);
                return res.status(200).send({message: "Template added successfully", template: {
                    campaignTemplateId: templateId,
                    templateName: templateName
                }});            
            }
            else{
                return res.status(400).send({message: "Max reached"});
            }
        });

【问题讨论】:

  • 那个return语句结束了forEach方法的回调函数;它不会结束外部函数的执行。您可以使用传统的 for 循环或 for-of 循​​环来解决问题。
  • 谢谢。这有帮助。我是 javascript 新手,在哪里可以阅读更多相关信息。我认为 foreach 只是在 javascript 中编写 for 循环的一种很好的方式

标签: node.js express pg-promise


【解决方案1】:

您可以使用some 函数来检查该名称是否已被使用。
这将避免使用forEach,如果条件有效,将阻止执行:

if (
  totalCustomTemplates.some(
    (element) => element.campaigntemplatename === templateName
  )
) {
  return res.status(400).send({
    message: 'This name is already in use. Please enter a new name',
  });
}

【讨论】:

  • some 将快捷地创建/检查数组
  • @Matt 谢谢你的提示
猜你喜欢
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 2015-12-25
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-22
  • 2013-04-12
相关资源
最近更新 更多