Search code examples
sqlnode.jsasync-awaitknex.js

Async where clause


I'm using knex 0.14.2 with Node 8 and I'm playing with async/await statement. But I just find a case where I need to build a where clause depending on a request: I build my main query, do a select and add a where to the main one, depending on the result. So I tried

mainQuery.where(async function() {
  const res = await knex('table').select();
  if(res.x) this.where('y', 'x');
})

but when tracing the queries, I saw the main one didn't have the where clause and the select was executed after it.

I suppose the await is not very well supported but is there a proper way to do such thing?

Thank you


Solution

  • How about:

    const res = await knex('table').select();
    await mainQuery.where(function() {
      if(res.x) this.where('y', 'x');
    })
    

    Knex will never support resolving internally builder method callbacks asychronously (in other words it will not support callback functions which would return promises).