我是 Promise 和 Q 的新手,我正在尝试转换在 node-mysql
中使用 query
的路由。以下是我的代码摘录:
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);
});
我正在尝试从不使用 promise 的现有设置中转换它,因此我知道连接设置正确并且查询有效。每当我尝试请求此路由时,我都会在 stderr 中收到相同的消息:
[TypeError: Cannot read property 'connectionConfig' of undefined]
我不知道它来自哪里,所以我不知道如何找到完整的堆栈跟踪。我还尝试了此代码的替代版本,其中我有自己的函数,而不是 console.log
和 console.error
,但该函数从未被调用,并且出现了相同的错误.
最佳答案
更新的答案:
当您denodeify
查询方法时,您可能会失去connection
的词法范围。
查看Q documentation它说这可能是一个问题:
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.nbind
代替:
var query = Q.nbind(connection.query, connection);
var promise = query("-- query ommitted --", [req.user.id]);
promise.then(console.log, console.error);
<小时/>
原答案:
查看node-mysql源代码,唯一访问connectionConfig
的位置是Pool.js 。所以我的猜测是,您对池的配置方式有疑问。
关于node.js - 为什么我的 Q promise 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28621940/