创建knex queryBuilder并稍后执行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建knex queryBuilder并稍后执行相关的知识,希望对你有一定的参考价值。

我希望创建一个queryBuilder对象,并推迟执行直到我准备好了。以下代码允许我在函数之间传递queryBuilder对象而不执行查询。

const getQueryBuilder = () => 
    knex({ client: "mysql2" }).queryBuilder();

const getBaseSelect = () =>
    getQueryBuilder().select().from('foo');

const getOne = () =>
   getBaseSelect().limit(1);

console.log(getBaseSelect()); // select * from `foo`
console.log(getOne());        // select * from `foo` limit 1

我的问题是如何执行我在queryBuilder中构建的查询?

或者是否有更好的方法在执行之前从多个同步函数构造查询?

谢谢。

答案

你想'推迟执行,直到你'准备好'。

它将取决于“准备好”的含义,但是当使用Promise完成所需操作时,您可以触发查询。

例如,如果您想在延迟5秒后执行查询,使用MDN Promise doc中的示例,您可以执行以下操作:

let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code.
  // In reality, you will probably be using something like XHR or an html5 API.
  setTimeout(function(){
    resolve("After this value is resolved with 5000ms delay, "); // Yay! Everything went well!
  }, 5000);
});

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  // You can fire your query here
  console.log(successMessage + "you can execute your query inside this then(..) function!");
  // execute(getBaseSelect());
});

以上是关于创建knex queryBuilder并稍后执行的主要内容,如果未能解决你的问题,请参考以下文章

Knex - 已经是最新的

如何在 Knex 查询中执行 MySQL 函数?

将 Postgres Heroku 与 Knex 连接不起作用

[嘲笑QueryBuilder时为NullPointerException

knex:从结果创建数组的适当方法是啥?

Knex:使用 FOREIGN KEY 创建迁移