Node.js 调用方法时,查询返回未定义

Node.js 调用方法时,查询返回未定义,node.js,node-mysql,Node.js,Node Mysql,节点mysql查询返回未定义 这是我的密码: Hash.prototype.GetHash = function() { var test; var connection = this.config.CreateConnection(); connection.connect(function(err){ if (err) throw err; else

节点mysql
查询
返回
未定义

这是我的密码:

Hash.prototype.GetHash = function()
    {
        var test;
        var connection = this.config.CreateConnection();
        connection.connect(function(err){
           if (err)
               throw err;
           else
           {
               var query = "SELECT hash FROM test WHERE id = 1";
               connection.query(query, function(err, rows, result){
                  if (err)
                      throw err;
                  else
                  {
                      test = rows[0].hash;
                      console.log(test);
                  }
               });
               connection.end(function(err){
                   if (err)
                       throw err;
               });
           }
        });
        return test;
    }
console.log将为我提供正确的结果
1a2b3c4d
。 所以当我将此方法调用到main方法时:

    var h = hash.GetHash();
    console.log(h);
控制台给我结果
未定义

所以我尝试从string类中强制转换、重新键入和创建一个新对象: 此对象
测试

比如:

但没有成功:\
有人能帮我解决这个问题吗?谢谢大家

Node.js是异步的,您的代码
Hash.prototype.GetHash=function(){}
将不工作,因为它在调用时立即返回值,但尚未执行。所以,当您打印测试时,它会给出未定义的

要使用函数计算并试图返回的
test
,必须在函数完成后使用callback with test作为参数来使用它。你必须对你的功能做一些改变

Hash.prototype.GetHash = function(callback){
//pass callback in arguments if you want it to be provided when calling
...  //compute test
//return test; Dont do return, do callback
callback(test);
}

//Your definition of callback should be
callback = function(h){
console.log(h);
}
请参阅教程以了解更多信息:


  • Node.js是异步的,您的代码
    Hash.prototype.GetHash=function(){}
    将无法工作,因为它在调用时立即返回值,但尚未执行。所以,当您打印测试时,它会给出未定义的

    要使用函数计算并试图返回的
    test
    ,必须在函数完成后使用callback with test作为参数来使用它。你必须对你的功能做一些改变

    Hash.prototype.GetHash = function(callback){
    //pass callback in arguments if you want it to be provided when calling
    ...  //compute test
    //return test; Dont do return, do callback
    callback(test);
    }
    
    //Your definition of callback should be
    callback = function(h){
    console.log(h);
    }
    
    请参阅教程以了解更多信息: