admin管理员组文章数量:1327937
I'm trying to work with MySQL in NodeJS. My entire app is built with promises, so I want to promisify the mysql
module as well.
So I have this:
Promise = require('bluebird');
var mysql = Promise.promisifyAll(require('mysql'));
Now, according to their API, the connect()
method accepts a single parameter, an err
callback to be called in case of connection error. My question is, how does that translate to promises?
Will the promise be resolved on error? Will it be rejected? Will I need to .catch()
it perhaps? How does that work?
I'm trying to work with MySQL in NodeJS. My entire app is built with promises, so I want to promisify the mysql
module as well.
So I have this:
Promise = require('bluebird');
var mysql = Promise.promisifyAll(require('mysql'));
Now, according to their API, the connect()
method accepts a single parameter, an err
callback to be called in case of connection error. My question is, how does that translate to promises?
Will the promise be resolved on error? Will it be rejected? Will I need to .catch()
it perhaps? How does that work?
1 Answer
Reset to default 8If 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");
// unment 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',
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.
});
本文标签: javascriptHow will a promisified mysql module work with NodeJSStack Overflow
版权声明:本文标题:javascript - How will a promisified mysql module work with NodeJS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742253057a2441120.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论