如何将 knex 与 async/await 一起使用?

How to use knex with async/await?

我正在尝试将 Knex 与 async/await 一起使用,因为 Knex 具有 Promise 接口。我的代码如下。

const db = makeKnex({
  client: 'mysql',
  connection: {
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
  },
  pool: { min: 0, max: 100 },
});

async function getUsers() {
  return await db.select()
  .from('users')
  .limit(10);
}
const res = getUsers();
console.log('KNEX', res);

我希望取回我的查询行,但输出是

KNEX Promise {
_c: [],
_a: undefined,
_s: 0,
_d: false,
_v: undefined,
_h: 0,
_n: false }

您应该在异步签名函数中调用 await。这是我使用的模式。

(async function(){
  const res = await getUsers();
  console.log('KNEX', res);
})()

异步函数 return 承诺,因此您需要将 return 从 getUsers 编辑的值视为承诺,因此 await 它们或使用 .then() 方法在他们身上:

getUsers().then((res) => console.log(res))
const functionName = async() => {
  let result = await db.select().('users').limit(10);
  return result;
}