栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用NodeJS和Postgres的事务链中的可选INSERT语句

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用NodeJS和Postgres的事务链中的可选INSERT语句

手动交易管理是一条危险的道路,请设法避免这种情况!;)

这是在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生成器



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446509.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号