If a method is a node "errback" with a single argument - it will be resolved with no parameters in the then
or alternatively be rejected with the err
passed to it. In the case of promisification, you can catch it with .error
or use a catch with Promise.OperationalError
.
Here is a simple approach:
function getConnection(){
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
return connection.connectAsync().return(connection); // <- note the second return
}
getConnection().then(function(db){
return db.queryAsync(....);
}).error(function(){
// could not connect, or query error
});
If this is for managing connections - I'd use Promise.using
- here is a sample from the API:
var mysql = require("mysql");
// uncomment if necessary
// var Promise = require("bluebird");
// Promise.promisifyAll(mysql);
// Promise.promisifyAll(require("mysql/lib/Connection").prototype);
// Promise.promisifyAll(require("mysql/lib/Pool").prototype);
var pool = mysql.createPool({
connectionLimit: 10,
host: 'example.org',
user: 'bob',
password: 'secret'
});
function getSqlConnection() {
return pool.getConnectionAsync().disposer(function(connection) {
try {
connection.release();
} catch(e) {};
});
}
module.exports = getSqlConnection;
Which would let you do:
Promise.using(getSqlConnection(), function(conn){
// handle connection here, return a promise here, when that promise resolves
// the connection will be automatically returned to the pool.
});