I\'m using sails 0.9.16 with Postgres and my question is: what is the best way to execute transaction using current API with promises? May be there is something better than:
The best way to deal with transactions is when they are wrapped properly by a promise library, because transaction logic maps perfectly into the promise event chain, one doesn't have to worry about when to do COMMIT
or ROLLBACK
, as it happens automatically.
Here's a complete example of how it works with pg-promise library:
var pgp = require('pg-promise')(/*options*/);
var cn = "postgres://username:password@host:port/database";
var db = pgp(cn); // database instance;
db.tx(t => {
// BEGIN has been executed
return t.batch([
t.one("insert into users(name) values($1) returning id", 'John'),
t.one("insert into users(name) values($1) returning id", 'Mike')
]);
})
.then(data => {
// COMMIT has been executed
console.log(data[0].id); // print id assigned to John;
console.log(data[1].id); // print id assigned to Mike;
})
.catch(error => {
// ROLLBACK has been executed
console.log(error); // print why failed;
});