NodeJS返回SQL查询以传递到另一个文件

时间:2018-05-30 16:52:58

标签: javascript sql node.js return-value

过去两天我一直在努力解决返回数据问题。我真的需要帮助才能将数据显示在另一个.js文件中 ,但我似乎无法这样做。

从我所做的所有研究中,我知道我需要回调函数才能进行返回。当我输出 file1.js 中的数据时,它会显示,这是正确的。

但是,我需要访问 file2.js 中的返回数据,但它没有显示。 我错过了什么吗?请帮助,非常感谢任何回应。谢谢。

请注意, file1.js 中的return语句接近代码的末尾。 此外,当在函数外部访问时,我的“res”数组总是为空。为什么会这样?

file1.js

var sql = require("mssql");

// Create a configuration object for our Azure SQL connection parameters
var dbConfig = {
 server: "***", // Use your SQL server name
 database: "***", // Database to connect to
 user: "***", // Use your username
 password: "***", // Use your password
 port: 1433,
 // Since we're on Windows Azure, we need to set the following options
 options: {
       encrypt: true
   }
};

var obj = {};
var res = [];

// This function connects to a SQL server, executes a SELECT statement,
// and displays the results in the console.
function getProducts(callback) {
 // Create connection instance
 var conn = new sql.ConnectionPool(dbConfig);

 conn.connect()
 // Successfull connection
 .then(function () {

   // Create request instance, passing in connection instance
   var req = new sql.Request(conn);

   // Call mssql's query method passing in params
   req.query("SELECT sp.product_name, count(ss.product_id) as 'quantity' " +
      "FROM smartcoolerstocks ss JOIN smartcoolerproducts sp " +
      "ON sp.product_id = ss.product_id " +
      "GROUP by sp.product_name ")
   .then(function (recordset) {
     //console.log(recordset.recordset);
     
     conn.close();
     //NEED CALLBACK FUNCTION
     console.log(recordset.recordset.length);

      for(var i = 0; i<recordset.recordset.length; i++ ){     
                    res.push(recordset.recordset[i]);
        }
     
     
     callback(null,recordset.recordset);
     process.exit(1);
   })
   // Handle sql statement execution errors
   .catch(function (err) {
     console.log(err);
     conn.close();
   })

 })
 // Handle connection errors
 .catch(function (err) {
   console.log(err);
   conn.close();
 });
 
}



//call Fn for db query with callback
getProducts(function(err,data){
        if (err) {
            // error handling code goes here
            console.log("ERROR : ",err);            
        } else {            
            // code to execute on data retrieval
            //console.log("result from db is : ",data.recordset);   
            //return data.recordset;
            return res;                
            
        }
        
});
console.log(res); //WHY IS THIS EMPTY HERE?



module.exports = {
  getProducts(){},
  
};      

  

块引用

file2.js

var myDB2 = require('./sqltest2');


console.log(myDB2.getProducts());

这是我在cmd中的输出: enter image description here

在'7'之后,没有任何表现。

如果我设法从file1.js获取file2.js中的返回数据,那么我的IDEAL输出应该是以下内容: enter image description here

1 个答案:

答案 0 :(得分:0)

  1. 您无法看到res,因为其竞争条件,console.log(res)早于recordset回调执行。

  2. file1.js已经执行了getProducts函数,因此没有返回file2.js的数据。

  3. var sql = require("mssql");
    // Create a configuration object for our Azure SQL connection parameters
    var dbConfig = {
      server: "***", // Use your SQL server name
      database: "***", // Database to connect to
      user: "***", // Use your username
      password: "***", // Use your password
      port: 1433,
      // Since we're on Windows Azure, we need to set the following options
      options: {
        encrypt: true
      }
    };
    
    var obj = {};
    var res = [];
    
    // This function connects to a SQL server, executes a SELECT statement,
    // and displays the results in the console.
    function getProducts(callback) {
      // Create connection instance
      var conn = new sql.ConnectionPool(dbConfig);
      conn.connect()
        // Successfull connection
        .then(function() {
          // Create request instance, passing in connection instance
          var req = new sql.Request(conn);
    
          // Call mssql's query method passing in params
          req.query("SELECT sp.product_name, count(ss.product_id) as 'quantity' " +
              "FROM smartcoolerstocks ss JOIN smartcoolerproducts sp " +
              "ON sp.product_id = ss.product_id " +
              "GROUP by sp.product_name ")
            .then(function(recordset) {
              conn.close();
              callback(null, recordset.recordset);
              process.exit(1);
            })
            // Handle sql statement execution errors
            .catch(function(err) {
              console.log(err);
              conn.close();
              callback(err, null);
            })
        }).catch(function(err) {
          console.log(err);
          conn.close();
          callback(err, null);
        });
    }
    
    module.exports = getProducts;

    file2.js

    var myDB2 = require('./sqltest2');
    myDB2(function(err, data){
      if( err ) console.log(err);
      else console.log(data);
    });