node.js - 为什么我的 Q promise 不起作用?

标签 node.js q node-mysql

我是 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.logconsole.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/

相关文章:

node.js - 使用 Firestore 分页

node.js - 在Nodejs中使用q(promises)模块时,then()返回的值是多少?

javascript - 我们如何使用 Async,在 nodeJS 中最好的方法是什么

transactions - bluebird node-mysql2事务

javascript - 从服务器端发出 HTTP 请求

Node.js 作为网关

node.js - 无法使用 Mongoose 在 MongoDB Atlas 数据库上读取/写入

javascript - 从 promise Angular 更新 ng-src

javascript - 困惑 : $q. when() 还是只调用一个没有它的函数?

javascript - 什么时候用??和 ?作为 node-mysql 中用于构建查询的占位符?