手动交易管理是一条危险的道路,请设法避免这种情况!;)
这是在pg-promise的帮助下正确执行操作的方法:
function(req, res) { db.tx(t => { // automatic BEGIN return t.one('INSERT_1 VALUES(...) RETURNING id', paramValues) .then(data => { var q = t.none('INSERT_2 VALUES(...)', data.id); if (req.body.value != null) { return q.then(()=> t.none('INSERT_3 VALUES(...)', data.id)); } return q; }); }) .then(data => { res.send("Everything's fine!"); // automatic COMMIT was executed }) .catch(error => { res.send("Something is wrong!"); // automatic ROLLBACK was executed });}或者,如果您更喜欢ES7语法:
function (req, res) { db.tx(async t => { // automatic BEGIN let data = await t.one('INSERT_1 VALUES(...) RETURNING id', paramValues); let q = await t.none('INSERT_2 VALUES(...)', data.id); if (req.body.value != null) { return await t.none('INSERT_3 VALUES(...)', data.id); } return q; }) .then(data => { res.send("Everything's fine!"); // automatic COMMIT was executed }) .catch(error => { res.send("Something is wrong!"); // automatic ROLLBACK was executed });}更新
在示例中,用ES7
async/ 替换了ES6生成器
await,因为pg-promise停止了从9.0.0版本开始支持ES6生成器



