创建knex queryBuilder并稍后执行

时间:2018-03-26 20:43:31

标签: javascript sql promise

我希望创建一个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中构建的查询?

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

感谢。

1 个答案:

答案 0 :(得分:0)

您希望将执行推迟到'你准备好了。'

这取决于“准备好”的含义,但您可以在使用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());
});




如果您正在等待多个承诺,可以使用Promise.all(..),如下所示:

Promise.all([myFirstPromise, mySecondPromise, myThirdPromise])
  .then((values) => {
    return execute(values[0], values[1], values[2])
  });