1

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.

Community
  • 1
  • 1
IvanSF
  • 301
  • 2
  • 8
  • You seem to be looking for `Promise.all` – Bergi Jul 29 '15 at 15:45
  • `Promise.all` (concurrent) or `Promise.each` sequential depending on what you'd like. – Benjamin Gruenbaum Jul 29 '15 at 21:34
  • @BenjaminGruenbaum the iterator is sequential, the array of promises passed to each may very well be concurrent: see comment http://bluebirdjs.com/docs/api/promise.each.html#comment-2661321645 – conny May 06 '16 at 07:24

2 Answers2

3

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);
});
James Moran
  • 624
  • 1
  • 7
  • 14
2

I used .map to get the desired effect.

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