Get return value when using call() with node.js

I am currently programming a socket server in node.js using the json-socket module, and am having some trouble.

Currently when a client connects to the server they send a command in a json object with some data for instance a login would look like this

{ type : 'login', data : { username: 'Spero78' } }

to deal with these requests i have a commands object

var commands = {
    'login' : authUser,
    'register' : userRegister
}

and these functions are called by 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 but the response var is always undefined and the "No Response!" message is always printed

Here is the authUser function

function authUser(data){
    console.log('Auth: ' + data.username);
    database.query('SELECT * FROM players WHERE 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 a better way of doing this? or am i missing something that is causing the objects to not return

database.query() is asynchronous, so when you call this function, nodejs don't wait the response of the callback to go to next instruction.

So the value tested on your condition is not the return in the callback, but of the whole authUser function, that's why it's always undefined.

You probably need tor refactor your code.