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