Express js request continues to process even after return statement

In the below code snippet even when the second if condition is met and this is returned

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

,the code still continues to execute and insert the data in the database.

Why is it happening and how can I stop that from executing any further?

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"});
            }
        });

Solution 1:

You could use the some function to check if the name is already used.
This will avoid the usage of the forEach and will block the execution if the condition is valid:

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