4

我正在使用基于einaros/ws构建的节点 ws 服务器。该服务器必须向数据库发送查询。为此,我正在使用felixge/node-mysql

当用户连接到服务器时,应该检查客户端是否仍然存在于数据库中。

这是一段有趣的代码:

console.log("client-liste ist leer");
var query = "SELECT name FROM spieler WHERE name='"+id+"' AND passwort='"+passwort+"'";
var result = queryToDatabase(query);
console.log(getTime() + "DB-Result Abfrage: " + result);

以及完成查询的代码:

var mysql = require('mysql');
var mysqlConnection = mysql.createConnection({
    host: dbHost,
    user: dbUser,
    password: dbPassword,
});

function queryToDatabase(anfrage) {
    mysqlConnection.connect();

mysqlConnection.query("USE " + db, function(err, rows, fields) {
    if (err) throw err;
});

mysqlConnection.query(anfrage, function(err, rows, fields) {
        if (err) throw err;
        console.log("rows as String - " + JSON.stringify(rows));
        return rows;

    });

    mysqlConnection.end();
}

控制台中的日志是:

client-liste ist leer
3.8.2012 - 15:29:0 - DB-Result Abfrage: undefined
rows as String - [{"name":"lukas"}]



有谁明白,为什么函数返回未定义?我还尝试通过简单的 setTimout 等待 Database-Connection 完成,但没有任何改变!

4

1 回答 1

5

You can't return a value from an asynchronous callback like the one used by query. You need to rewrite queryToDatabase so it takes a callback as its second argument and calls it with rows when the query is successful. Then your main code needs to look like:

queryToDatabase(query, function(result) {
     console.log(getTime() + "DB-Result Abfrage: " + result);
   });

In reality, all your code that depends on the query result will need to go into that callback.

In practice, you'd want the callback to take two arguments: an error status and a result, with the error status being null if the query was successful.

于 2012-08-03T16:25:01.617 回答