Tecnico Tecnico - 4 months ago 9
Node.js Question

Incorrect order execution on my server TCP (node.js)

I attached my server code:

var net = require('net');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('MyBBDD.db');
var prueba = '';

function get_kw_actual(nombre,callback){
stmt = db.prepare("SELECT kw_actual FROM usuarios WHERE usuario = ?");
stmt.bind(nombre);
stmt.get(function(error,row){
if(error){
throw err;
}
else{
if(row){
entero=row.kw_actual;
callback(entero);
}
else{
console.log("error");
}
}
});
}

var server = net.createServer(function(socket) {
console.log("Recibo peticion");

socket.on('data', function (data) {
get_kw_actual('Pepe',function(resultado){
console.log('resultado es: ' + resultado);
prueba = '' + resultado;
})
socket.write(prueba);
});

socket.on('close', function () {
console.log('Connection closed');
});

});
server.listen(1337, '192.168.1.101');


In my server, I receive a request, I call to my function "get_kw_actual" I get a number of my database and finally I respond with the result.
The problem is that it runs first "socket.write(prueba);" than:

stmt.get(function(error,row){
if(error){
throw err;
}
else{
if(row){
entero=row.kw_actual;
callback(entero);
}
else{
console.log("error");
}
}
});


So... the execution is not executed in the correct order and the result is not correct.
Somebody know how can I solve it?
Thanks in advance.

Best regards.

Answer

Node.js code runs asynchronously. The code in the callback get_kw_actual returns immediately but the callback will run at some later time, when the database operation has completed. What you want to do is put socket.write inside of the callback, like this:

socket.on('data', function (data) {
    get_kw_actual('Pepe',function(resultado){
        console.log('resultado es: ' + resultado);
        socket.write(resultado);
    })
});

Also note that you're using a global variable prueba in your code, which will get clobbered when you have multiple clients running against your server. Do not use global variables like this in node.