KnexJS循环查询

时间:2015-07-29 15:34:11

标签: node.js promise knex.js

我是Node,KnexJS和promises的新手,我正在尝试构建一个查询项目的简单循环,然后添加与它们相关的图片。

我看了这个答案,虽然它教了一些我认为不适用于我的案例: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 });
    });
});

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

2 个答案:

答案 0 :(得分:2)

添加到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);
});

答案 1 :(得分:1)

我使用.map来获得所需的效果。

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