Home > Software engineering >  cannot send response out of db.query
cannot send response out of db.query

Time:09-27

router.get('/detalle/(:id)', (req, res) => {
    let vehiculo_base
    db.query("select b.nombre, count(b.nombre) AS n_vehiculos from base AS b, vehiculo AS v where b.id = v.id_base AND b.id_flota = "   req.params.id , function(err, result){
        if (err) throw err
        vehiculo_base = result
    })
    res.send(vehiculo_base)
})

I want to add multiple query results to the response, but the variable vehiculo_base is undefined out of db.query

CodePudding user response:

db.query is async function so try like this.

router.get('/detalle/(:id)', (req, res) => {
    let vehiculo_base
    db.query("select b.nombre, count(b.nombre) AS n_vehiculos from base AS b, vehiculo AS v where b.id = v.id_base AND b.id_flota = "   req.params.id , function(err, result){
        if (err) throw err
        vehiculo_base = result
        res.send(vehiculo_base)
    })
})

second approach

router.get('/detalle/(:id)', async (req, res) => {
      let vehiculo_base
      var vehiculo_base = await db.query("select b.nombre, count(b.nombre) AS n_vehiculos from base AS b, vehiculo AS v where b.id = v.id_base AND b.id_flota = "   req.params.id);
       res.send(vehiculo_base)
  })

CodePudding user response:

You can rewrite this route as

router.get('/detalle/(:id)', async (req, res) => {
  try{
    let vehiculo_base = await 
    db.query("select b.nombre, count(b.nombre) AS n_vehiculos from base AS b, vehiculo AS v where b.id = v.id_base AND b.id_flota = "   req.params.id)
    res.send(vehiculo_base);
  }catch(error){
    res.send(error);
  }   
});

CodePudding user response:

The problem is that query is async, and you are returning the result with res.send right after executing it synchronously.

You should return the result once it is available.

router.get('/detalle/(:id)', (req, res) => {
    db.query("select b.nombre, count(b.nombre) AS n_vehiculos from base AS b, vehiculo AS v where b.id = v.id_base AND b.id_flota = "   req.params.id , function(err, result){
        if (err) throw err
        res.send(result)
    })
    
})

You should add logs in the future to understand the flow, and read a bit about async and sync execution. And how javascript execution works.

  • Related