Pergunta

Using NodeJS, Express, Socket.io & node-mysql on a server at the moment. Currently having a problem with one of the functions on the server not returning any data at all. I'm at my ends wit trying to figure this out.

Function Code;

It is supposed to return "c", but is not working. The console.log is actually showing the ID and username.

function LOGIN_USER(a,b) {
    // 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);
            return c;
    });

}

Other code.

socket.on('login user', function(data) {
        var c;

        c = LOGIN_USER(data.username,data.password);
        console.log(c.ID,c.USR);
    });

After this console.log is where my nodeJS server crashes. Saying it can't display undefined etc.. etc. Can't for the life of me figure this out, any help is most appreciated!! :)

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top