Knex await 如何执行数据库查询?

How does Knex await execute a database query?

我正在尝试了解 await 关键字在 KNEX 中的使用方式。举个例子:

knex.schema.createTable( ... );

这将 return this 这是 SchemaBuilder 的一个实例。它不会在数据库中执行 create table 查询。但是,如果我坚持并 await 在它前面。

await knex.schema.createTable( ... );

这将在数据库中执行创建查询。

我的理解是 await 用于等待 promise 解决,但在这种情况下,感觉好像发生了其他事情,因为没有 await 函数不会 return一个承诺。

这是如何工作的?

如果你想知道 knex 如何只在你在构造前面写 await 时才发出请求,那么请看这里。

在幕后,knex 使用 pattern returns 具有 then 字段的对象。

const asyncFunction = (delay) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      return resolve(delay);
    }, delay);
  })
}

const builder = (delay) => {
  return {
    then: async (resolve) => {
      const result = await asyncFunction(delay);
      return resolve(result);
    }
  }
}

const main = async () => {
  const array = [];
  for(let i=0; i<10; i++) {
    array.push(builder(i));
  }
  console.log('array', array);
  console.log('array[0]', array[0]);
  console.log('await array[0]', await array[0]);
  console.log('Promise.all for array', await Promise.all(array));
}

main();

本次执行的结果将是如下输出到控制台

array [
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] },
  { then: [AsyncFunction: then] }
]
array[0] { then: [AsyncFunction: then] }
await array[0] 0
Promise.all for array [
  0, 1, 2, 3, 4,
  5, 6, 7, 8, 9
]

如您所见,then 函数内的代码将不会被调用,直到使用 await 关键字或其他等待 Promise 的方式。