The documentation with promises is horrible. What's the correct way to connect with a database handle, and run something like an express route?
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'
}
);
So now I have dbh, which is a Promise
. What do I do with in my routes...
app.get('stuff' function () {
// How do I use it here?
});
app.get('otherstuff' function () {
// How do I use it here?
});
Is the right way to do something like...
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.
};
} );
Because if so, that actually lo
First of all, having only one connection shared by the server process horrible, not sure why firebase documentation advocates it. You should use a conncetion pool from which you request a connection for every http request.
If you want to employ the suggested anti-pattern anyway, the way to use it "with promises" is just like they document:
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;
});
Again, the usage in express routes is same as they document:
app.get('stuff' function (req, res, next) {
database.queryAsync("select cast(? as integer) from rdb$database", 123)
.then(function(result) {
});
});
I agree the bluebird docs are not that good, 2.0 improves the documentation a lot and adds promisification tutorial, more examples and so on.
The transaction example from: https://github.com/hgourvest/node-firebird#using-transaction
would be:
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;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.