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