node js:无法从函数返回值

时间:2017-03-14 11:32:39

标签: javascript database database-connection

我无法理解如何从节点js中的函数获取返回值。请在下面找到代码(我能够在控制台日志中获取查询结果,但无法找到ow以返回该值并在调用函数后将其存储到任何变量中)

调用函数main:

dbConnection("xxx","xxx","xxx","xxx","50000","select xxx,xxx,CURRENCY from xxx where AccountID='85433333'")

设置数据库连接的功能:

function dbConnection(dbname,hostname,UserID,Password,Port,query,callback)
{
      var ibmdb = require('ibm_db');
      ibmdb.open("DATABASE="+dbname+";HOSTNAME="+hostname+";UID="+UserID+";PWD="+Password+";PORT="+Port+";PROTOCOL=TCPIP", function (err,conn)
      {
          if (err) return console.log(err);
          var a= executeQuery(conn,query,function(err,data)
          {
            return data
          });
      });
}

执行查询的功能:

function executeQuery(conn,query,cb)
{
    conn.query(query, function (err, data)
    {
        if (err) console.log(err,data);
        else
            console.log(data);
    });
    //return callback(data);
};

1 个答案:

答案 0 :(得分:0)

这是一个异步函数,所以你需要使用回调来返回如下所示。并调用

之类的调用
dbConnection("xxx","xxx","xxx","xxx","50000","select xxx,xxx,CURRENCY from xxx where AccountID='85433333'", function(err, data) {
    console.log(data)
})

function dbConnection(dbname,hostname,UserID,Password,Port,query,callback)
{
  var ibmdb = require('ibm_db');
      ibmdb.open("DATABASE="+dbname+";HOSTNAME="+hostname+";UID="+UserID+";PWD="+Passw    ord+";PORT="+Port+";PROTOCOL=TCPIP", function (err,conn)
  {
      if (err) return console.log(err);
      var a= executeQuery(conn,query,function(err,data)
      {
        callback(err, data)
      });
  });
}