promisified mysql模块如何与NodeJS一起使用? [英] How will a promisified mysql module work with NodeJS?

查看:254
本文介绍了promisified mysql模块如何与NodeJS一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 - 它将被解析为no 中的参数,然后,或者通过传递给它的错误被拒绝。在promisification的情况下,您可以使用 .error 来捕获它,或者使用带有 Promise.OperationalError 的catch。

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

这篇关于promisified mysql模块如何与NodeJS一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆