NodeJ中的异步函数

时间:2014-09-28 18:44:03

标签: node.js function asynchronous

我写了一个服务器(它应该获取请求并发送响应)和另一个连接到db的服务器(并且具有一些用于不同查询的函数)。

项目有RoutingPath.Js,它只根据url的路径路由到所需的函数。 ServerLogic.Js初始化db-server,一些函数(根据RoutingPath)和查询函数:

var SqlServer = require("./ConnectToSql");
var request = SqlServer.ConnectToSql();

if (SqlServer == null)
{
  console.log ("+++++++SqlServer = null");
}
else
{
  console.log ("-------SqlServer" + SqlServer);
}

if (request == null)
{
  console.log("!!!!!!!!!");
}
else
{
  console.log("$$$$$$$$$$"+request);
}

function Welcome(params)
{
  console.log("ServerLogic: Welcome to My Trip server with: " + params.user + "=" + params.password);
  var tmp = RunQuery("SELECT GroupName FROM Groups");
  console.log("Welcome: " + tmp);
  //return "Welcome to My Trip server with: " + params.user + "=" + params.password;
  return tmp;
}

function RunQuery(sqlquery)
{
  console.log("---request: " + request + "--------");

  request.query(sqlquery, function(err, recordset) {
      if (err)
      {
        console.log(err);
        console.log("----End Query Error-------");
      }
      else
      {
        console.log(recordset);
        console.log("----End recordset-------");
        return recordset;
      }
    });
}

exports.Welcome = Welcome;

我有ConnectToSql.Js连接到db:

var sql = require('C:/Program Files/nodejs/node_modules/mssql'); 

var config = {
  user: '',
  password: '',
  server: '',
  database: '',
  }
};

function ConnectToSql()
{
  var connection = new sql.Connection(config, function(err) {

    if (err)
    {
      console.log(err);
    }
    else
    {
      var request = new sql.Request(connection);
      console.log("#########" + request);
      return request;
    }
  });
}

exports.ConnectToSql = ConnectToSql;

这是我的输出:

-------SqlServer[object Object]
!!!!!!!!!
#########[object Object]

所以我的问题是输出的顺序: 为什么:“######### [object Object]”不是第二个输出(然后第三个输出将是:$$$$$$$$$$ [object Object])

1 个答案:

答案 0 :(得分:1)

原因request == null是因为ConnectToSql()是非阻塞的,并且在建立连接之前立即返回。在使用异步代码时,您应该传递回调。例如:

function ConnectToSql(callback) {
  var connection = new sql.Connection(config, function(err) {
    if (err)
      return callback(err);
    callback(null, connection);
  });
}

然后在您的主服务器逻辑中:

var sql = require('C:/Program Files/nodejs/node_modules/mssql'),
    SqlServer = require('./ConnectToSql');

var connection;

function Welcome(params, callback) {
  console.log('ServerLogic: Welcome to My Trip server with: ' + params.user + '=' + params.password);
  RunQuery('SELECT GroupName FROM Groups', callback);
}

function RunQuery(sqlquery, callback) {
  if (!connection) {
    SqlServer.ConnectToSql(function(err, conn) {
      if (err)
        return callback(err);
      connection = conn;
      RunQuery(sqlquery, callback);
    });
    return;
  }

  var request = new sql.Request(connection);
  request.query(sqlquery, callback);
}

exports.Welcome = Welcome;

然后使用Welcome(),如:

Welcome(params, function(err, recordset) {
  // ...
});