【发布时间】: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