javascript - Get return value when using call() with node.js -
i programming socket server in node.js using json-socket module, , having trouble.
currently when client connects server send command in json object data instance login this
{ type : 'login', data : { username: 'spero78' } }
to deal these requests have commands object
var commands = { 'login' : authuser, 'register' : userregister }
and these functions called server.on
server.on('connection', function(socket) { console.log('client connected'); socket = new jsonsocket(socket); socket.on('message', function(message) { if(message.type != undefined) { if(commands[message.type]){ var response = commands[message.type].call(this, message.data); if(response != undefined){ console.log(response); socket.sendmessage(response); } else { console.log("no response!"); } } else { console.log('unexpected command!'); } } }); });
the functions return javascript objects response var undefined , "no response!" message printed
here authuser function
function authuser(data){ console.log('auth: ' + data.username); database.query('select * players username = ?', [data.username], function(err, results) { if(results.length < 1){ console.log('bad login!'); var response = { type : 'badlogin', data : { //... } } return response; } var player = results[0]; var response = { type : 'player', data : { //... } } return response; }); }
is there better way of doing this? or missing causing objects not return
database.query()
asynchronous, when call function, nodejs don't wait response of callback go next instruction.
so value tested on condition not return in callback, of whole authuser
function, that's why it's undefined.
you need tor refactor code.
Comments
Post a Comment