Home > Blockchain >  how to stop multiple query Node JS
how to stop multiple query Node JS

Time:12-28

After checking if the name already exists, the program keeps running to the next query and still insert data (also shows an error because it sends multiple responses). How to make it stop after it run if (results.rowCount > 0) ?

const addCategory = (req, res) => {
    let { name } = req.body

    //check if name exist
    pool.query(queries.checkNameExists, [name], (error, results) => {
        if (error) throw error
        if (results.rowCount > 0) {
            return res.status(409).send(`Category ${name} already exists!`)
        }
    })

    //insert new category
    pool.query(queries.addCategory, [name], (error, results) => {
        if (error) throw error
        res.status(201).send("Category created succesfully!")
    })
}

CodePudding user response:

First thing that you cannot return anything from callback and the problem is your program is executing both the queries at the same time and because of that multiple response will be send for single request , here i have the solution for your problem

const addCategory = async(req, res) => {
    let { name } = req.body
    //check if name exist
    const exist = await pool.query(queries.checkNameExists, [name]);
    if(exist){
        return res.status(409).send(`Category ${name} already exists!`)
    }
    //insert new category
    await pool.query(queries.addCategory, [name]);
    return res.status(201).send("Category created succesfully!")
    
}
  • Related