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.
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);
});
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;
});
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.