查询何时开始执行,以及如何阻止它执行?

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

当我有这样的代码时:

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

我已经定义了查询,并希望在同一行中得到结果。如果我这样做:

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

那么查询是在第一行开始执行还是在实际等待结果时开始执行?

从常规的承诺语义来看,查询似乎从第 1 行开始执行,而第 3 行只是等待结果。

但是,我怀疑这不可能发生,因为 knex('table').select()knex('table').select().where(...) 都是有效查询,并且 knex 无法知道语句何时结束,所以我'我不确定它将如何准备适当的 SQL 查询。

那么查询实际上是从第 3 行开始执行的吗?这是否违反了承诺语义?

在不执行查询的情况下定义查询的正确方法是什么?只是为了避免等待?

实际上在 knex 存储库问题中找到了答案:https://github.com/knex/knex/issues/4163#issuecomment-746028366

knex chain returns thenable. then method call starts query. await is just a syntax sugar on top of promises/thenables.

knex.schema.createTable( ... ).then(() => {})

所以是的,在调用 .then 之前查询不会开始执行,防止它执行的最佳方法是避免调用它。

我的建议是使用一个函数,本质上是为以后保存调用。

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

在调用函数 query 之前,knex 查询不应 运行。 这种方法也与库无关。