即使在 return 语句之后,Express js 请求仍继续处理
Express js request continues to process even after return statement
在下面的代码片段中,即使满足第二个 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 = `, [
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 (, , )',[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"});
}
});
您可以使用 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',
});
}
在下面的代码片段中,即使满足第二个 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 = `, [
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 (, , )',[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"});
}
});
您可以使用 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',
});
}