I want to promisify node-postgres' pg.connect
method along with the inner connection.query
method provided in the callback.
I can .promisify
the latter, but I need to implement the first one manually (if I'm missing something here, please explain).
The thing is, I'm not sure if this code is correct or should be improved? The code is working, I just want to know if I'm using Bluebird as meant.
// aliases
var asPromise = Promise.promisify;
// save reference to original method
var connect = pg.connect.bind(pg);
// promisify method
pg.connect = function (data) {
var deferred = Promise.defer();
connect(data, function promisify(err, connection, release) {
if (err) return deferred.reject(err);
// promisify query factory
connection.query = asPromise(connection.query, connection);
// resolve promised connection
deferred.resolve([connection,release]);
});
return deferred.promise;
};
I suggest to modify Petka Antonov solution a bit
here
'pg[key]
wrapped up intry-catch
block becausepg[key]
can retrunerror
when attempt to accesspg['native']
Update for bluebird 3:
The
pg.connectAsync(...).spread(function(connection, release) { ... })
call will not work anymore, because the API of bluebird has changed: http://bluebirdjs.com/docs/new-in-bluebird-3.html#promisification-api-changes .The problem is that
promisifyAll
in bluebird 3 does not handle multiple arguments by default. This results in the.spread()
call reporting a TypeError like the following:To solve this, you can explicitly enable multiple arguments for
connect
/connectAsync
. Do the following after all the promisifying stuff mentioned above:By now there are a number of libraries which do this for you:
Throw all that horrible callback code away, then do this somewhere in your application initialization:
Later in anywhere you can use the pg module as if it was designed to use promises to begin with: