简体   繁体   English

为什么我的Q承诺不起作用?

[英]Why isn't my Q promise working?

I'm new to promises and Q, and I'm trying to convert a route that uses query in node-mysql . 我是Promise和Q的新手,我正在尝试转换在node-mysql中使用query的路由。 Here are excerpts from my code: 这是我的代码的摘录:

var Q = require('q');
// connection defined elsewhere

router.get('/', function(req, res) {
    var query = Q.denodeify(connection.query);
    var promise = query("-- query ommitted --", [req.user.id]);
    promise.then(console.log, console.error);
});

I'm trying to convert this from an existing set up that doesn't use promises, so I know the connection is set up properly and the query is valid. 我正在尝试从不使用Promise的现有设置中转换此设置,因此我知道连接设置正确且查询有效。 Whenever I try to request this route, I get the same message in stderr: 每当我尝试请求此路由时,都会在stderr中得到相同的消息:

[TypeError: Cannot read property 'connectionConfig' of undefined]

I don't know where it's coming from so I'm not sure how to find the full stacktrace. 我不知道它来自哪里,所以我不确定如何找到完整的堆栈跟踪。 I also tried an alternate version of this code where I had my own function instead of console.log and console.error , but this function was never called and the same error appeared. 我还尝试了此代码的替代版本,在该版本中,我拥有自己的函数而不是console.logconsole.error ,但是从未调用此函数,并且出现了相同的错误。

Updated answer: 更新的答案:

You're probably losing the lexical scope to connection when you denodeify the query method. 当您使查询方法denodeify时,您可能会失去connection的词法作用域。

Looking at the Q documentation it says this can be an issue: 查看Q文档,它可能是一个问题:

If you are working with methods, instead of simple functions, you can easily run in to the usual problems where passing a method to another function—like Q.nfcall—"un-binds" the method from its owner. 如果您使用的是方法而不是简单的函数,则可以轻松地遇到将方法传递给另一个函数(例如Q.nfcall)的“常见问题”,即将方法从其所有者“取消绑定”。

To fix this try using Q.nbind instead: 要解决此问题,请尝试使用Q.nbind代替:

var query = Q.nbind(connection.query, connection);
var promise = query("-- query ommitted --", [req.user.id]);
promise.then(console.log, console.error);

Original answer: 原始答案:

Looking at the node-mysql source, the only place connectionConfig is accessed is in Pool.js . 纵观节点MySQL源代码,唯一的地方connectionConfig访问是在Pool.js So my guess would be that you've got an issue with how the pool is being configured. 因此,我的猜测是您在配置池方面遇到了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM