0

带有承诺的文档是可怕的。连接数据库句柄并运行类似快速路由的正确方法是什么?

var Promise = require('bluebird');                
var db2 = Promise.promisifyAll(fb);               

var dbh = db2.connectAsync({                       
    host: '127.0.0.1',                            
    database: 'CAFW.FDB',                         
    user: 'SYSDBA',                               
    password: 'pw'                          
  }                                               
);

所以现在我有了 dbh,它是一个Promise. 我在我的路线中做什么......

app.get('stuff' function () {
  // How do I use it here?
});


app.get('otherstuff' function () {
  // How do I use it here?
});

做类似的事情的正确方法是......

var db2 = Promise.promisifyAll(fb);

dbh.then( function (dbh) {

   // This is asyncronous code, Express doesn't use promises
   app.get('stuff', function () {
      // And, here I have DBH -- but this is pyramid code again.
      // Do I avoid this pattern? Or, is this required
   };

   app.get('otherstuff', function () {
      // dbh here.
   };

} );

因为如果是这样,那实际上

4

1 回答 1

0

首先,服务器进程只共享一个连接太可怕了,不知道为什么firebase文档提倡它。您应该使用一个连接池,从该池中为每个 http 请求请求连接。

如果您无论如何都想使用建议的反模式,那么“使用承诺”使用它的方式就像他们记录的那样:

db2.connectAsync({                       
    host: '127.0.0.1',                            
    database: 'CAFW.FDB',                         
    user: 'SYSDBA',                               
    password: 'pw'                          
}).then(function(database) {
    Promise.promisifyAll(database);
    // Their docs have implicit global assignment 
    global.database = database;
});

同样,快速路线中的用法与他们记录的相同:

app.get('stuff' function (req, res, next) {
     database.queryAsync("select cast(? as integer) from rdb$database", 123)
        .then(function(result) {

        });
});

我同意 bluebird 文档不是那么好,2.0 改进了很多文档并添加了 Promisification 教程、更多示例等等。


交易示例来自:https ://github.com/hgourvest/node-firebird#using-transaction

将会:

database.startTransactionAsync().bind({})
    .then(function(transaction) {
        // Holy shit this is inefficient, why can't they just expose the classes
        // like every other module
        Promise.promisifyAll(transaction.constructor.prototype);
        this.transaction = transaction;
        return transaction.queryAsync("select cast(? as integer) from rdb$database", 123);
    })
    .then(function(result1) {
        this.result1 = result1;
        return this.transaction.queryAsync("select cast(? as integer) from rdb$database", 456);
    })
    .then(function(result2) {
        this.result2 = result2;
        return this.transaction.commitAsync();
    })
    .then(function() {
        console.log(this.result1[0]);
        console.log(this.result2[0]);
    })
    .catch(function(err) {
        this.transaction.rollback();
        throw err;
    });
于 2014-05-28T10:31:11.067 回答