0

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

所以我有这个:

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

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

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

4

1 回答 1

8

如果方法是带有单个参数的节点“errback” - 它将在没有参数的情况下解析,then或者err通过传递给它而被拒绝。在 promisification 的情况下,您可以.error使用 catch 或使用 catch来捕获它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- 这是来自 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.
});
于 2014-07-17T08:19:23.977 回答