Javascript promisified mysql模块将如何与NodeJS一起工作?
我正在尝试在NodeJS中使用MySQL。我的整个应用程序都是用承诺构建的,所以我也想承诺使用Javascript promisified mysql模块将如何与NodeJS一起工作?,javascript,mysql,node.js,promise,bluebird,Javascript,Mysql,Node.js,Promise,Bluebird,我正在尝试在NodeJS中使用MySQL。我的整个应用程序都是用承诺构建的,所以我也想承诺使用mysql模块 所以我有这个: Promise = require('bluebird'); var mysql = Promise.promisifyAll(require('mysql')); 现在,根据他们的API,connect()方法接受一个参数,err回调,以便在连接出错时调用。我的问题是,这如何转化为承诺 承诺会因错误而得到解决吗?它会被拒绝吗?我可能需要.catch()它吗?这是如何工
mysql
模块
所以我有这个:
Promise = require('bluebird');
var mysql = Promise.promisifyAll(require('mysql'));
现在,根据他们的API,connect()
方法接受一个参数,err
回调,以便在连接出错时调用。我的问题是,这如何转化为承诺
承诺会因错误而得到解决吗?它会被拒绝吗?我可能需要.catch()
它吗?这是如何工作的?如果一个方法是一个带有单个参数的节点“errback”-它将在中没有参数的情况下解析,然后或者被拒绝,并将err
传递给它。在Promission的情况下,您可以使用.error
捕捉它,或者使用带有Promise.OperationalError
的捕捉
以下是一个简单的方法:
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
});
这样你就可以:
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.
});
有没有一种方法可以进行异步查询,比如getConnectionAsync(),我可以在promise.using函数中调用它。或者我必须在promise.using()中创建新的promise。
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.
});