【问题标题】:How will a promisified mysql module work with NodeJS?一个承诺的 mysql 模块将如何与 NodeJS 一起工作?
【发布时间】:2014-09-07 22:58:29
【问题描述】:

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

所以我有这个:

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

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

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

【问题讨论】:

    标签: javascript mysql node.js promise bluebird


    【解决方案1】:

    如果一个方法是一个带有单个参数的节点“errback”——它将在then 中没有参数的情况下被解析,或者通过传递给它的err 被拒绝。在 Promisification 的情况下,您可以使用 .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 - 这是来自 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.
    });
    

    【讨论】:

    • 有没有办法像 getConnectionAsync() 那样进行异步查询,我可以在 promise.using 函数中调用它。或者我必须在 promise.using() 中创建新的承诺。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    相关资源
    最近更新 更多