Returning response in validation Express indicates error and continues the flow

I am validating through a middleware that the quantity of product required by the client is not greater than the quantity of product in stock.

The validation is correct, the message is displayed indicating that there is less stock than the user requires, but even if the message is displayed, the execution does not stop, it reaches the controller and saves the information.

This is my middleware:

let productHasStock =  async ( req, res, next ) => {
    try { 
        const details = req.body.detail;

        const product = await details.map( async detail => {
            let product = await Product.findById( detail._id );
 
            if (product.stock < detail.quantity) {
                console.log('stock error');
                return res.status(401).json({
                    msg: 'Stock error'
                })
            }
        })

        next();
    
    } catch (error) {
        res.status(401).json({
            msg: 'La petición es incorrecta'
        })
    }

}

const checkStock = async (id, quantity) => {

    let product = await Product.findById( id );
    return (quantity > product.stock) ? false : true;
};

module.exports = {
    productHasStock
}

In addition to this I get an error stating: Cannot set headers after they are sent to the client

error on console

I tried passing this logic to the controller but I get exactly the same errors so much so that it doesn’t stop executing like the error in the console.

Thanks for your help.