一个promisified mysql 模块将如何与NodeJS 一起工作?

2021-12-29 00:00:00 node.js javascript mysql promise bluebird

我正在尝试在 NodeJS 中使用 MySQL.我的整个应用程序都是用 promise 构建的,所以我也想对 mysql 模块进行 promisify.

I'm trying to work with MySQL in NodeJS. My entire app is built with promises, so I want to promisify the mysql module as well.

所以我有这个:

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

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

Now, according to their API, the connect() method accepts a single parameter, an err callback to be called in case of connection error. My question is, how does that translate to promises?

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

Will the promise be resolved on error? Will it be rejected? Will I need to .catch() it perhaps? How does that work?

推荐答案

如果一个方法是一个带有单个参数的节点errback" - 它将在 then 中不带任何参数的情况下被解析,或者替代被传递给它的 err 拒绝.在 promisification 的情况下,您可以使用 .error 捕获它或使用 Promise.OperationalError 捕获它.

If a method is a node "errback" with a single argument - it will be resolved with no parameters in the then or alternatively be rejected with the err passed to it. In the case of promisification, you can catch it with .error or use a catch with 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 的示例:

If this is for managing connections - I'd use Promise.using - here is a sample from the 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.
});

相关文章