A nicer API on node-postgres transactions
varpg=require('pg.js');varpgTransact=require('pg-transact');functiontransaction(client,cb){// everything in here is run as a transactionclient.query('SELECT NOW() as when',function(err,result){if(err){// passing an error to the callback does a rollback on the transactionreturncb(err);}// passing a `null` error and a result will resolve the transaction as the resultcb(null,result);});}pg.connect(connectionString,function(err,client,done){if(err){throwerr;}pgTransact(client,transaction,done).then(console.log,console.error);});It also will work with a returned promise:
varpg=require('pg.js');varpgTransact=require('pg-transact');functiontransaction(client){returnnewPromise(function(resolve,reject){client.query('SELECT NOW() as when',function(err,result){if(err){returnreject(err);}resolve(result);});});}pg.connect(connectionString,function(err,client,done){if(err){throwerr;}pgTransact(client,transaction,done).then(console.log,console.error);});