本文介绍了KnexJS查询循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Node,KnexJS和Promise还是很陌生,我正在尝试构建一个简单的循环来查询项目,然后添加与它们相关的图片.

I'm very new with Node, KnexJS and promises and I'm trying to build a simple loop that queries items and then adds the pictures associated with them.

我看着这个答案,虽然它教了一些我认为不适合我的情况的东西:

I looked at this answer and while it teaches a few things I don't think it works for my case: Knex Transaction with Promises

到目前为止,我有这个:

So far I have this:

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 });
    });
});

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

Which is obviously wrong, but I just don't know the approach in these cases.

推荐答案

添加到IvanSF的答案中,您只需将Promise.all()包裹起来,然后res.send()响应即可.像这样:

Adding to IvanSF's answer, you can simply wrap a Promise.all() around that, to then res.send() the response. Like so:

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);
});

这篇关于KnexJS查询循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 23:11