Search code examples
node.jsqnode-mysql

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. 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. Whenever I try to request this route, I get the same message in 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.


Solution

  • Updated answer:

    You're probably losing the lexical scope to connection when you denodeify the query method.

    Looking at the Q documentation it says this can be an issue:

    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.

    To fix this try using Q.nbind instead:

    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. So my guess would be that you've got an issue with how the pool is being configured.