1

我写了一个nodejs服务器。

app.get("/admin", function (req, res) {
    var connection, value;
    connection = mysql.createConnection({
        host: "******",
        user: "*****",
        password: "****",
        database: "YaAMP",
        insecureAuth: true
    });
    value = mySQLgetValue("SELECT property, value FROM config WHERE property = 'primeMult'", connection);
    console.log("Return Value" + value); //returns "[object Object]"
    connection.end();
    return res.render("admin", {
        title: "YaAMP"
    });
});

还有一个mySQLgetValue从 MySQL 数据库中获取值的函数,它应该从数据库中返回一个特定的值。

mySQLgetValue = function (queryString, connection) {
    var value;
    value = 0;
    return connection.query(queryString, function (err, rows, fields) {
        console.log("Value " + rows[0].value); //Returns correct value
        return value += rows[0].value;
    });
};

console.log函数中的mySQLgetValue从数据库返回正确的值。但是函数调用返回一个Objectconsole.log打印“[object Object]”。

怎么了?

4

1 回答 1

5

The console.log() is variadic, so use a comma instead of +.

console.log("Return Value", value);

The + does string concatenation, which calls the .toString() on the object, which is why you were getting [object Object].


You can't get the return value from the callback that you're passing to connection.query, because you're not the one invoking that function.

Instead, define another parameter to your function to receive a callback function that is invoked inside the callback passed to connection.query. This will replace the return statement.

app.get("/admin", function (req, res) {
    var connection, value;
    connection = mysql.createConnection({
        host: "******",
        user: "*****",
        password: "****",
        database: "YaAMP",
        insecureAuth: true
    });

    var q = "SELECT property, value FROM config WHERE property = 'primeMult'";

     // Pass a callback-----------------v
    mySQLgetValue(q, connection, function(val) { console.log(val); });

    connection.end();

    return res.render("admin", {
        title: "YaAMP"
    });
});

        // callback parameter ------------------------v
mySQLgetValue = function (queryString, connection, callback) {
    var value;
    value = 0;
    return connection.query(queryString, function (err, rows, fields) {
        console.log("Value " + rows[0].value);

         // Invoke your callback
        callback(value += rows[0].value);
    });
};
于 2013-04-29T14:52:43.853 回答