3

客户要求提供动态信息,这些信息将提供到同一网页中的 2 个表格或列表中。例如,比较 2 个对象或文章。

翡翠模板

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 个街区:

router.get('/', function(req, res, next) {
    res.render('./index', { foo_table: table1, bar_table: table2});
};
  • 我得到的唯一想法是console.log但无法将查询结果传递给模板(var 表不存储查询结果)。

  • 我在“then”或异步函数中创建的任何变量都不是持久的。

  • JSON.stringify 或 parse 不会转换这些嵌套函数的结果。

  • 在模板变量定义(footable: *, bartable: *)之后回调函数或创建函数不起作用。

  • 由于查询是 thenable 我找不到任何方法来转换为可存储的,或者相反,从各种 thenable 查询中收集结果以提供最终信息并呈现模板变量。

  • 加载页面时是否必须为每个表创建单独的 AJAX 方法?

  • 我想从一开始就使用 get 方法为整个页面提供服务。

4

1 回答 1

1

如果您正在使用(或您使用的库基于)Bluebird(或任何其他承诺库),那么您应该能够这样做:

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()(如例所示)。

于 2015-08-06T19:04:02.527 回答