0

我有一个带有 Express 和 mysql 的 NodeJS。我放了一个通用 sql 函数,所以我多次调用它:

exports.selectCommand=function(table,cols,cond){
    var connection = mysql.createConnection({
        host     : hostname,
        database: databasename,
        user     : username
    });
    try{
        connection.query("SELECT "+cols+" As data from "+table+" where "+cond+" ", function(err, rows, fields) {
            if (err) return "sorry, an error accoured. Please try again later";
            if(rows.length!=0){
            cmd = rows[0].data.toString();
            }
        });
    }catch (e){console.log(e.message);}
    connection.end();
    return cmd; };

我通过它发送查询,但它返回我发送的第一个查询的问题。

我把上面的函数放在另一个文件中,我称之为:

var db=require('./db.js');
..........
exports.psModel=function(){
    var cmddata="";
    cmddata=db.selectCommand("cmd","value","cmd='textbox'");
}
4

1 回答 1

2

your return cmd returns probably before the query is processed. The call is asynchronous. Try to place the return statement within the callback (and the connection end as well). Something like this:

try{
    connection.query("SELECT "+cols+" As data from "+table+" where "+cond+" ",
        function(err, rows, fields) {
            connection.end();
            if (err) return "sorry, an error occurred. Please try again later";
            if(rows.length!=0){
              cmd = rows[0].data.toString();
              return cmd;
            }
        });
    }catch (e){console.log(e.message);}
于 2013-07-08T13:42:51.727 回答