无法从sql数据库中读取javascript函数获取返回数组

时间:2016-03-29 16:39:11

标签: javascript node.js express

我已经通过代码调试以检查以确保我从node.js中的sql连接中获取数据。但是我无法通过此函数返回结果。循环遍历行时,它会将项目添加到数组中,但我在其中注释了值显示正确的行...为什么此函数返回空白数组[]?

function execute_stp_getconfigurationsbyuserid(userid, callback)
{
    var results = [];
    var Connection = require('tedious').Connection;
    var config = {
    };

    function item(id,name)
    {
        this.id = id;
        this.name = name;

        return this;
    }

    var Request = require('tedious').Request
    var TYPES = require('tedious').TYPES;

    var connection = new Connection(config);

    var myCallback = function(err,data){
        connection.on('connect', function(err) {

            var request = new Request("stp_GetConfigurationsByUserId @UserId", function(err) {
                if (err) {
                    console.log(err);}
            });

            request.addParameter('UserId', TYPES.Int, userid);

            request.on('row', function(columns) {
                var itm = new item(columns[0].value, columns[2].value);
                results.push(itm);
                //HAS THE CORRECT VALUE HERE
                console.log(results);
            });

            request.on('done', function(rowCount, more) {
                console.log(rowCount + ' rows returned');
                myCallback(null,results);
            });

            connection.execSql(request);

        });
    }

}

通过以下方式调用函数:

router.get('/getuserconfigurations', function(req, res, next) {
    var config_ddl = execute_stp_getconfigurationsbyuserid(1);
    console.log("Getting user configurations....")
    console.log(config_ddl);
    res.send(JSON.stringify(config_ddl));
});

1 个答案:

答案 0 :(得分:1)

节点异步工作。执行返回结果的时间,上面的语句不需要完成。尝试使用回调来传递/处理数据。 请参阅此链接nodeJs callbacks simple example

编辑:代码可以修改为

var callback = function(err, data){
  console.log(data);
}

function execute_stp_getconfigurationsbyuserid(userid, callback)
{
    var results = [];
    var Connection = require('tedious').Connection;
    var config = {
    };

    function item(id,name)
    {
        this.id = id;
        this.name = name;

        return this;
    }

    var Request = require('tedious').Request
    var TYPES = require('tedious').TYPES;

    var connection = new Connection(config);

 
  connection.on('connect', function(err) {

    var request = new Request("stp_GetConfigurationsByUserId @UserId", function(err) {
      if (err) {
        console.log(err);}
    });

    request.addParameter('UserId', TYPES.Int, userid);

    request.on('row', function(columns) {
      var itm = new item(columns[0].value, columns[2].value);
      results.push(itm);
      //HAS THE CORRECT VALUE HERE
      console.log(results);
    });

    request.on('done', function(rowCount, more) {
      console.log(rowCount + ' rows returned');
      callback(null,results);
    });

    connection.execSql(request);

  });
   

}