Node.js 使用NodeJS和Postgres在事务链中可选插入语句

Node.js 使用NodeJS和Postgres在事务链中可选插入语句,node.js,postgresql,transactions,pg-promise,Node.js,Postgresql,Transactions,Pg Promise,我正在使用NodeJS/Postgres构建一个简单的webapp,它需要在数据库中进行3次插入 为了控制语句链,我使用了pg transaction 我的问题是,我必须始终运行前两次插入,但我有条件运行第三次插入 也许我的代码可以以更好的方式构建(欢迎提出建议) 下面是一个伪代码: 功能(请求、恢复){ var tx=新交易(客户); tx.on(“错误”,死亡); tx.begin(); tx.query('INSERT_1 VALUES(…)返回id',paramValues,函数(er

我正在使用NodeJS/Postgres构建一个简单的webapp,它需要在数据库中进行3次插入

为了控制语句链,我使用了pg transaction

我的问题是,我必须始终运行前两次插入,但我有条件运行第三次插入

也许我的代码可以以更好的方式构建(欢迎提出建议)

下面是一个伪代码:

功能(请求、恢复){
var tx=新交易(客户);
tx.on(“错误”,死亡);
tx.begin();
tx.query('INSERT_1 VALUES(…)返回id',paramValues,函数(err,result){
如果(错误){
tx.回滚();
res.send(“出了点问题!”);
返回;
}
var paramValues2=result.rows[0].id;
tx.query('INSERT_2 VALUES(…)',paramValues2,函数(err2,result2){
如果(错误){
tx.回滚();
res.send(“出了点问题!”);
返回;
}
//问题是(我不想总是运行最后一条语句)
//如果我不运行它,我将错过tx.commit()
如果(req.body.value!=null){
tx.query('INSERT_3 VALUES(…)',paramValues3,函数(err3,result3){
如果(错误){
tx.回滚();
res.send(“出了点问题!”);
返回;
}
tx.commit();
res.send(“一切正常!”);
});
}
});
});

}
手动事务管理是一条危险的道路,试着避开它!;)

以下是如何在以下人员的帮助下正确执行此操作:

或者,如果您更喜欢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
        });
}
更新


在本例中,将ES6生成器替换为ES7
async
/
wait
,因为pg promise从9.0.0版开始停止支持ES6生成器

您确定在上一次插入中是
'insert_3 VALUES(…)',paramValues2
而不是一些
'insert_3 VALUES(…)',paramValues3
?i、 您是否需要使用第一个查询的结果来执行最后一个查询?这正是我所需要的。刚刚测试过,效果非常好。谢谢你完整的回答!
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
        });
}