Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Knex.js from running a query object when returning it from an async function?

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?

like image 891
d-vine Avatar asked Nov 06 '22 15:11

d-vine


1 Answers

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.

like image 87
Mikael Lepistö Avatar answered Nov 14 '22 23:11

Mikael Lepistö