I have a node.js backend that constructs DB queries dynamically from various inputs using Knex.js. Some of the inputs need to be processed asynchronously. My problem is, that I can't return a knex query object from an async function (or of course in a Promise resolve function) because this triggers the execution of the query. Currently I need to process all my async inputs before handing them to the query building functions but that really limits their composability. Is there a way to prevent Knex from executing a query object in an async context?
You need to wrap builder to a function or to an object:
async function returnsQueryBuilder() {
return { builder : knex('mytable').where('foo', 'bar') };
}
const query = (await returnsQueryBuilder()).builder;
Because async functions actually wraps and resolves returned values/promises/thenables and knex
query builder is a thenable
(https://promisesaplus.com/ chapter 1.2) it gets reasolved automatically.
For the same reason you can also directly await query builder to get result from the built query. Without knex query builder being thenable
this would not work either:
// returns all the rows of the table
const result = await knex('table');
So as I said the only option is to not return query builder instance directly, but wrap it to something that is not thenable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With