The MySQL query is asynchronous, so you cannot use a return value in it. In asynchronous programming, you must use a callback, because a return statement will stop execution:
function LOGIN_USER(a, b, callback) {
// a = username
// b = password
var c = [];
connection.query("SELECT ID FROM GAME_PLAYER WHERE USR = '" + a + "' AND PWD = '" + b + "'", function (err, rows, field) {
if (err) throw err;
for (var i in rows) {
c.ID = rows[i].ID;
c.USR = a;
}
console.log(c.ID + " " + c.USR);
callback(c);
});
}
And then this is how you'd use it:
socket.on('login user', function(data) {
LOGIN_USER(data.username, data.password, function(c) {
console.log(c.ID, c.USR);
});
});
When you use a return statement in a callback function, it acts as if you used return;
, which in turn just stops the execution of a function. This is how the callback is working:
You are passing values to a function, as well as another function:
var func = function() {
// do something
};
LOGIN_USER(a, b, func);
When the user login has completed, the login function will call the function that was passed to it:
function LOGIN_USER(a, b, callback) {
// do some work
callback();
};
So you passed func()
to LOGIN_USER()
, and LOGIN_USER()
called func()
when it completed.