客户要求提供动态信息,这些信息将被转换到同一网页中的 2 个表格或列表中。比方说,比较 2 个对象或文章。
Jade 模板
extends layout.jade
block content1
div= foo_table
block content2
div= bar_table
数据库查询
var table1 = db.query('select * from table where ...')
.then(function (result){
console.log(result);
});
var table2 = db.query('select * from table where ...')
.then(function (result){
console.log(result);
});
//I DON'T WANT TO SEND TO CONSOLE, JUST GET THE DATA, BUT IT IS ASYNCHRONOUS
使用 return 而不是 console.log 不会返回数据集。
.then(function (result){
return(result);
});
No variable defined inside then() is persistent.
路由器代码
如果我使用此方法,它会起作用,但是......:
router.get('/', function(req, res, next) {
db.query('select * from table where ...')
.then(function (result){
res.send(result);
});
问题是它只能提供 1 个查询。
我想同时服务 2 个区 block :
router.get('/', function(req, res, next) {
res.render('./index', { foo_table: table1, bar_table: table2});
};
我唯一想到的是 console.log 但没有办法 将查询结果传递给模板(var tables 不 存储查询结果)。
我在“then”或异步函数中创建的任何变量都不是 坚持不懈。
JSON.stringify 或 parse 不转换这些嵌套函数的结果。
在模板变量之后回调函数或创建函数 定义(footable:*,bartable:*)不起作用。
由于查询是可行的,所以我找不到任何方法将其转换为 可存储的,或者相反,从各种可查询的结果中收集结果 提供最终信息并呈现模板变量。
当 页面加载了吗?
我想从一开始就使用 get 方法提供整个页面。
最佳答案
如果您正在使用(或您使用的库基于)类似 Bluebird 的东西(或任何其他 promise 库)那么你应该能够这样做:
Promise.all([
db.query('select * from foo where ...'),
db.query('select * from bar where ...')
])
.spread(function(foo, bar) {
/* prepare data as you need them */
res.render('./index', { foo_table: foo, bar_table: bar});
});
Promise.all
异步“等待”直到传递数组中的两个方法(数据库查询)完成并返回,然后将两个结果一起传递给传递给 .spread 的回调()
(如 this 示例)。
关于javascript - 将多个查询呈现到同一个 jade 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31863356/