I'm struggling to implement Bluebird promises with MySql. I think I'm close, but my problems are starting to compound and I could use some help getting back on track. I had this code all working with callbacks, but I have jacked it up with promises.
The current problem is that it doesn't like the "then" on my query, as in:
conn.query("DO DB STUFF").then(function(result){});
First, I have a connection.js file that looks like this. I've added some comments in the code.
(function () {
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit: 10,
host: "localhost",
user: "myuser",
password: "password",
database: "dbName"
});
// stole this from http://stackoverflow.com/questions/24797314/how-will-a-promisified-mysql-module-work-with-nodejs
exports.getConnection = function(){
return pool.getConnectionAsync().disposer(function(connection){
try{
connection.release();
} catch (e) {}
});
};
})();
Then I have a "db access" file that looks like this:
var Promise = require("bluebird");
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
var connection = require("./connection");
var common = require("../../domain/common");
exports.isKnownBadTicker = function (stockSymbol) {
if (stockSymbol == null) { return false; }
else {
var ticker = common.standardizeStockSymbol(stockSymbol);
var query = "SELECT COUNT(*) AS count FROM BadTicker WHERE Symbol = '" + ticker + "';";
// it doesn't like the conn.query(query).then . . . says that "then" is not valid, and so I tried to just return the response of the query - which also doesn't work.
Promise.using(connection.getConnection(), function (conn) {
return conn.query(query)[0]["count"] > 0;
// conn.query(query).then(function (result) {
// return result[0]["count"] > 0;
// });
});
}
};
I feel like I'm close, but I just can't quite put it together. Can anyone help me straighten this mess out?
Also, I'm not sure I'm doing some other things right, like, can I return a boolean in a function that also returns promises? Feel free to straighten me out if you see that I've gone all whacky. Any help is appreciated.
Vic