1

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

Castas115
  • 11
  • 1
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Edric Sep 27 '22 at 09:03

3 Answers3

0

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.

noitse
  • 1,045
  • 9
  • 27
0

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)
  })
  • Hi, only the second option should work for me but this happens: TypeError: Converting circular structure to JSON --> starting at object with constructor 'Query' | property '_timer' -> object with constructor 'Timer' --- property '_object' closes the circle Do you know what this means and how could I fix it? – Castas115 Sep 29 '22 at 08:13
0

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