简体   繁体   English

如何使用Jade渲染node-mssql语句的返回值?

[英]How do I render return values of a node-mssql statement with Jade?

I've got a Node.js server with Express and Jade running. 我有一个运行Express和Jade的Node.js服务器。 On an HTTP request the server will execute the following function: 在HTTP请求上,服务器将执行以下功能:

function home(req, res) {

  res.render("site/index", {recordset: recordset}); //render the Jade template
}

Now I would like to pass in an array to the above recordset variable that I can loop through in Jade to populate a drop-down on my html page. 现在,我想将数组传递给上面的记录集变量,我可以在Jade中循环遍历该变量以填充html页面上的下拉列表。 I've retrieved the desired array like so: 我已经检索到所需的数组,如下所示:

function runSQLSelect() {
      sql.connect(config.db, function(err) {
      var request = new sql.Request();
      request.query("select MyColumn FROM MyTable", function(err, recordset) {
        console.log(recordset);
        });
      });
}

What is a proper way to asynchronously run the SQL query and pass the subsequent result into my Jade template? 异步运行SQL查询并将后续结果传递到我的Jade模板中的正确方法是什么?

You will have the res.render in the callback from query. 查询的回调中将具有res.render。

function runSQLSelect(callback) {
      sql.connect(config.db, function(err) {
      var request = new sql.Request();
      request.query("select MyColumn FROM MyTable", function(err, recordset) {
        console.log(recordset);
        callback(recordset);
        });
      });
}

function home(req, res) {
  runQSQLSelect( function(result) {
      res.render("site/index", {recordset: result}); //render the Jade template
  });
}

Note, you may want to have your callback invoked in an async fashion, using setImmediate , you also might consider having your runSQLSelect callback make use of the standard node practice of accepting two parameters callback(err,data) . 注意,您可能希望使用setImmediate以异步方式调用回调,也可以考虑让runSQLSelect回调利用接受两个参数callback(err,data)的标准节点实践。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM