从异步函数返回查询对象时,如何防止Knex.js运行查询对象? [英] How to prevent Knex.js from running a query object when returning it from an async function?

查看:165
本文介绍了从异步函数返回查询对象时,如何防止Knex.js运行查询对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个node.js后端,该后端使用Knex.js从各种输入动态构造数据库查询.一些输入需要异步处理.我的问题是,我无法从异步函数(或者当然在Promise resolve函数中)返回knex查询对象,因为这会触发查询的执行.目前,我需要先处理所有异步输入,然后再将其交给查询构建函数,但这确实限制了它们的可组合性.有没有一种方法可以防止Knex在异步上下文中执行查询对象?

I have a node.js backend that constructs DB queries dynamically from various inputs using Knex.js. Some of the inputs need to be processed asynchronously. My problem is, that I can't return a knex query object from an async function (or of course in a Promise resolve function) because this triggers the execution of the query. Currently I need to process all my async inputs before handing them to the query building functions but that really limits their composability. Is there a way to prevent Knex from executing a query object in an async context?

推荐答案

感谢MikaelLepistö的回答,我对如何解决这个问题有了一个想法.正如他指出的那样,Knex查询由于具有then函数而成为thenables.实际上,JavaScript await关键字会调用您提供给它的任何对象的then函数,无论是否承诺.因此,为了防止在await(或.then())上执行查询,您可以删除/重命名查询then函数.例如

Thanks to Mikael Lepistö's answer I got an idea how to work around this. As he pointed out Knex queries are thenables by virtue of having a then function. The JavaScript await keyword actually calls the then function of any object you present to it, regardless if promise or not. So in order to prevent query execution on await (or .then()) you can remove/rename the queries then function. E.g.

const getQuery = async () => {
  const qb = knex("users")
    .select("id")
    .limit(100);
  qb.promise = qb.then;
  qb.then = undefined;
  return qb;
};

const query = await getQuery();
console.log(query.toString());
console.log(await query.promise());

更新,警告:不要在家里的孩子身上尝试这个 s:)

我有义务在评论中指出米凯尔的有效批评.这是编写您自己的包装器类的骇人听闻且潜在的危险捷径,并且可能使您的代码更难以理解.但我也坚持认为,在我的特定用例中键入正确的TypeScript,这是一种有效且有效的解决方案.

I feel obliged to point to Mikael's valid criticism in the comments. This a hacky and potential dangerous shortcut to writing your own wrapper class and might make your code harder to understand. But I also stand by my assessment that with proper TypeScript typing in my specific use case it's a valid and efficient solution.

UPDATE2 :现在无需弄乱原型:).在实例上将.then设置为undefined即可.

UPDATE2: Now without messing up the prototype :). Setting .then to undefined on the instance works just fine.

这篇关于从异步函数返回查询对象时,如何防止Knex.js运行查询对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆