How to return variable in nodejs

1

I have this function: I do not know how to return.

var getVariablesOriginales=function(nombre){
var objBD = BD();
let res=[];


        objBD.query("select ID_U from usuario u where u.'NOMBRE'=?",[nombre], function(err, rows, fields) {

        objBD.query("SELECT tiempo, variableb FROM tiempos t where t.'ID_U'=? Group By variableb,tiempo",[rows[0].ID_U], function(err, rows, fields) {

            for (var i = 0; i < rows.length; i++) {
                    res.push(rows[i].tiempo);
                };  
        });
        });

    return res;             
}

What I do to return the result of that query, I copy row in an auxiliary variable res and then I can return.

is it possible to return variable row directly?

    
asked by hubman 28.01.2017 в 16:29
source

1 answer

1

What you are trying to achieve is not possible in the way you are doing it, basically because the answer you want to return is asynchronous while what you return in the function is a synchronous response.

The asynchrony in Javascript is one of the most important concepts in the language that you should know.

In this case, what you are trying to do is obtain data from a database (external application independent of the language) whose response time is undefined and susceptible to errors.

Let's understand what happens:

var getVariablesOriginales = function(nombre) {
  var db = BD();
  var res = [];

  // Iniciar consulta a la base de datos:
  db.query("query 1...", [nombre], function(err, rows, fields) {
    // La ejecucion de esta funcion depende del tiempo de respuesta de la bd

    db.query("query 2...", [rows[0].ID_U], function(err, rows, fields) {
      // La ejecucion de esta tambien

      for (var i = 0; i < rows.length; i++) {
        res.push(rows[i].tiempo);
      };
    });
  });

  // Cuando se ejecute el siguiente return, el codigo anterior aun no 
  // se ha ejecutado porque la base de datos aun no ha enviado su respuesta.
  return res;
  // Javascript no espera a nadie.
}

The solution for this is to turn your function into an asynchronous function. Javascript offers you two ways:

Use a callback in the style of node.js:

function queryDB(parameters, done) {
  var db = DB();
  db.query('query 1...', [data], function(err, rows) {
    if (err) return done(err);
    db.query('query 2...', [rows[0].something], function(err, rows) {
      if (err) return done(err);
      return done(null, rows);
    });
  });
}

// Uso:
queryDB('something', function(err, res) {
  if (err) console.error(err);
  console.log(res);
});

Return a promise :

function queryDB(parameters) {
  var db = DB();

  return new Promise(function(resolve, reject) {
    db.query('query 1...', [data], function(err, rows) {
      if (err) return reject(err);
      db.query('query 2...', [rows[0].something], function(err, rows) {
        if (err) return reject(err);
        return resolve(rows);
      });
    });
  });
}

// Uso:
var res = queryDB('something');

res.then(function(res) {
  // Manejar la respuesta:
  console.log(res);
});

res.catch(function(err) {
  // Ocurrio algun error...
  console.log(err);
});
    
answered by 28.01.2017 / 22:21
source