How to access knex query results

Viewed 20892

Using knex with express, how can I access the results of a knex query?

Example:

var bots = []

response = knex.select('id', 'name').from('robots')
  .then(function(robots){
    console.log(robots);
    bots = robots
  });

console.log(bots)

This will log the robots but not not update the bots array, which is empty.

EDIT:

As a synchronous workaround, in an express route, I stuck the express block inside the knex block:

router.get('/robots', function (req, res) {

  response = knex.select('id', 'name').from('robots').then(function(bots){

    res.render('robots/index', {
      page_title: 'All Robots',
      robots: bots
    }); // res.render

  }); // knex.select

}); // router.get

Is this the recommended pattern?

2 Answers
Related