0

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!")
    })
}
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – skara9 Dec 28 '21 at 04:55
  • 2
    Put the second query inside the callback from the first and then you can properly control whether it executes or not. `pool.query()` is asynchronous and non-blocking so the way it is written now, then next one executes in parallel with the first one. If you put the second inside the completion callback of the first, then you can control it. – jfriend00 Dec 28 '21 at 05:11
  • 1
    Also, `if (error) throw error` is not proper error handling. You need to send an error status and you MUST send some response to every incoming request. – jfriend00 Dec 28 '21 at 05:22
  • You are doing both queries in parallel. Just do the second query **AFTER** the first query instead of doing it in parallel (that means putting the second query INSIDE the `(error, results) => { ...` function) – slebetman Dec 28 '21 at 05:27

1 Answers1

2

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