Search code examples
javascriptpromiseknex.js

When does a query start executing, and how to prevent it from executing?


When I have some code like this:

async f() {
  ...
  const result = await knex('table').select().where(...)
  ...
}

I have defined the query and am expecting the result in the same line. If instead I do this:

async f() {
  ...
  const query = knex('table').select().where(...) // line 1
  // do something else; line 2
  const result = await query // line 3
  ...
}

then does the query start executing at the first line or when the result is actually awaited?

From regular promise semantics, it would seem that query starts executing at line 1, and line 3 just awaits the result.

However, I suspect that this can't happen because knex('table').select() and knex('table').select().where(...) are both valid queries, and knex wouldn't have a way of knowing when the statement ends, so I'm not sure how it'll prepare the appropriate SQL query.

So does the query actually start executing at line 3 instead? Is this in violation of promise semantics?

And what's the correct way to define the query without executing it? Just to avoid awaiting it?


Solution

  • My suggestion would be to use a function, essentially saving the call for later.

    async f() {
      ...
      const query = () => knex('table').select().where(...) // line 1
      // do something else; line 2
      const result = await query() // line 3
      ...
    }
    

    The knex query shouldn't be run until the function query is called. This approach is also library agnostic.