copy the value of a variable does not work in nodejs

2

My function is:

var copia;
objBD.query('select max(ID_U) AS max_id from usuario ', function(err, rows, fields) { 
    copia=rows[0].max_id;
    console.log(rows[0].max_id); 
});
console.log(copia);

variable copia shows the value undefined , does not copy the% number rows[0].max_id ; when I print console.log(rows[0].max_id); , it shows a different number.

NOTE: copia is a global variable.

    
asked by hubman 30.09.2016 в 14:05
source

2 answers

1

This is how your program is actually running

var copia;
objBD.query('select max(ID_U) AS max_id from usuario ');
console.log(copia); // Aquí aun no tiene valor
// Unos segundos después cuando la consulta termina 
copia=rows[0].max_id; // Aquí es donde le asignas el valor
console.log(rows[0].max_id); 

You are trying to print its value before the query ends for that reason it will not have the value you expect.

You have to move all the logic that depends on this variable copia for this block

objBD.query('select max(ID_U) AS max_id from usuario ', function(err, rows, fields) { 
    copia=rows[0].max_id;
    // Luego que tiene valor trabajas con ella
    // El resto del código va aquí
});
    
answered by 30.09.2016 / 14:26
source
3

You are not understanding the nature of the JavaScript language. JavaScript is an asynchronous language, that is, a block of code is not always aligned with the timeline of the next block.

In JavaScript there is something called callback . A callback is a function that can be passed to another without altering the timeline of the main function. This is the nature of asynchronous programming, being able to have several processes in parallel.

What is happening?

What happens is that both console.log(copia) and the callback function(err, rows, fields) { ... } are executed in different timelines , therefore, it is normal that copia still does not have the assigned value in the callback.

What can I do?

To make the code more modular, you can pass rows[0].max_id to a function.

objBD.query('select max(ID_U) AS max_id from usuario ', function(err, rows, fields) { 
    afterQuery(rows[0].max_id); 
});

// seguir con el flujo
function afterQuery(maxId) {
  copia = maxId;
}

ES6 / 8

If you want a more "procedural" style, you can support yourself in the latest versions of EcmaScript (6,7,8) using polyfills.

With these modules, your code would look like this:

// flujo natural
let rows = await getMaxId();
copia = rows[0].max_id;

function async getMaxId() {
  return objBD.query('select max(ID_U) AS max_id from usuario');
}
    
answered by 30.09.2016 в 14:26