我正在尝试在NodeJS中使用MySQL.我的整个应用程序都是用promises构建的,所以我也想宣传MysqL模块.
所以我有这个:
Promise = require('bluebird');
var MysqL = Promise.promisifyAll(require('MysqL'));
现在,根据他们的API,connect()方法接受单个参数,在连接错误的情况下调用错误的回调.我的问题是,这如何转化为承诺?
承诺会在出错时解决吗?它会被拒绝吗?我可能需要.catch()吗?这是如何运作的?
解决方法:
如果一个方法是一个带有单个参数的节点“errback” – 它将在当时没有参数的情况下被解析,或者被传递给它的err被拒绝.在promisification的情况下,您可以使用.error捕获它或使用带Promise.OperationalError的catch.
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 – 这是来自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;
哪个会让你这样做:
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.
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。