一个有前途的 mysql 模块将如何与 NodeJS 一起工作?

How will a promisified mysql module work with NodeJS?

提问人:Madara's Ghost 提问时间:7/17/2014 最后编辑:Benjamin GruenbaumMadara's Ghost 更新时间:12/25/2014 访问量:4836

问:

我正在尝试在 NodeJS 中使用 MySQL。我的整个应用程序都是用承诺构建的,所以我也想承诺这个模块。mysql

所以我有这个:

Promise = require('bluebird');
var mysql = Promise.promisifyAll(require('mysql'));

现在,根据他们的 API,该方法接受单个参数,即在连接错误时调用的回调。我的问题是,这如何转化为承诺?connect()err

承诺会在错误时得到解决吗?会被拒绝吗?我可能需要它吗?这是如何工作的?.catch()

JavaScript MySQL 节点 .js 承诺 蓝鸟

评论


答:

8赞 Benjamin Gruenbaum 7/17/2014 #1

如果一个方法是带有单个参数的节点“errback”,那么它将在没有参数的情况下被解析,或者被传递给它时被拒绝。在承诺的情况下,您可以用 catch 来捕捉它或使用 .thenerr.errorPromise.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
});

如果这是为了管理连接 - 我会使用 - 这是 API 的示例:Promise.using

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.
});

评论

0赞 pitu 2/11/2016
有没有办法进行像getConnectionAsync()这样的异步查询,我可以在promise.using 函数中调用它。或者我必须在 promise.using() 中创建新的 promise。