首页 > 解决方案 > Knex await 如何执行数据库查询?

问题描述

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

knex.schema.createTable( ... );

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

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

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

我的理解是,await它用于等待承诺解决,但在这种情况下,感觉就像发生了其他事情,因为不await使用函数不会返回承诺。

这是如何运作的?

标签: javascriptnode.jsdesign-patternsasync-awaitknex.js

解决方案


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

在幕后,knex使用 apattern返回带有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


推荐阅读