promises如何与异步库一起使用?

时间:2014-05-27 11:00:04

标签: javascript promise bluebird

承诺的文件很糟糕。连接数据库句柄和运行类似快速路由的正确方法是什么?

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

} );

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

1 个答案:

答案 0 :(得分:0)

首先,只有一个连接由服务器进程共享可怕,不知道为什么firebase文档提倡它。您应该使用一个conncetion池,您可以从中请求每个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) {

        });
});

我同意蓝鸟文档不是那么好,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;
    });