【问题标题】:KnexJS loop of queriesKnexJS 查询循环
【发布时间】:2015-07-29 15:34:11
【问题描述】:

我对 Node、KnexJS 和 Promise 非常陌生,我正在尝试构建一个简单的循环来查询项目,然后添加与它们关联的图片。

我查看了这个答案,虽然它教了一些东西,但我认为它不适用于我的情况:Knex Transaction with Promises

到目前为止,我有这个:

router.get('/', function(req, res, next) {
  knex('parts').where(req.query)
    .orderBy('date_updated', 'DESC')
    .then(function(data){

      for (var k in data) {
        knex('photos')
          .select()
          .where('part_id', data[k].id)
          .then(function(photos){
            data[k].photos = photos;
          });
      }
      return data;

    })
    .then(function(data){
      res.render('parts/index', { title: 'Express', data: data, query: req.query });
    });
});

这显然是错误的,但我只是不知道在这些情况下的方法。

【问题讨论】:

标签: node.js promise knex.js


【解决方案1】:

添加到 IvanSF 的答案,您可以简单地将 Promise.all() 包裹起来,然后将 res.send() 包裹起来。像这样:

Promise.all(rows.map(row => {
    return knex('table')
        .select('*').where('row_id', row.id)
        .then(table => {
            row.table = table;
            return row;
        });
})).then(response => {
    res.send(response);
});

【讨论】:

    【解决方案2】:

    我使用 .map 来获得想要的效果。

        .map(function(row) {
          return knex('photos')
            .select()
            .where('part_id', row.id)
            .then(function(photos) {
              row.photos = photos;
              return row;
            });
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 2017-08-28
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多