Knex: How to use knex with async/await?

Created on 10 Dec 2016  ·  3Comments  ·  Source: knex/knex

I'm trying to use Knex with async/await since Knex has a Promise interface. My code is below.

const db = makeKnex({
  client: 'mysql',
  connection: {
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
  },
  pool: { min: 0, max: 100 },
});

async function getUsers() {
  return await db.select()
  .from('users')
  .limit(10);
}
const res = getUsers();
console.log('KNEX', res);

I expected to get the rows of my query back, but the output is

KNEX Promise {
_c: [],
_a: undefined,
_s: 0,
_d: false,
_v: undefined,
_h: 0,
_n: false }

Most helpful comment

This is not related to knex, but just general stuff about async / await and promises. Closing...

All 3 comments

you should probably wrap

const res = getUsers();
console.log('KNEX', res);

into async function and put await before getUsers();

(async function() {
  const res = await getUsers();
  console.log('KNEX', res);
}())

also think about try/catch for error handling (bubbling up)

Hmm this works

async function test(){
    const res = await getUsers();
    console.log('KNEX', res);
}
test();

This is not related to knex, but just general stuff about async / await and promises. Closing...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

npow picture npow  ·  3Comments

arconus picture arconus  ·  3Comments

mishitpatel picture mishitpatel  ·  3Comments

rarkins picture rarkins  ·  3Comments

saurabhghewari picture saurabhghewari  ·  3Comments