【发布时间】:2021-02-18 03:56:56
【问题描述】:
我已经在 Postgresql 中编写了一个事务块(通过 node-postgres)并且它工作正常,尽管我想问是否可以(以及如何)在事务块中放置一个 if-else 条件。
这是我当前的代码(按预期工作):
async function execute() {
// Promise chain for pg Pool client
const client = await pool
.connect()
.catch(err => {
console.log("\nclient.connect():", err.name);
process.exit();
});
//Initiate the Postgres transaction
await client.query("BEGIN");
try {
... <<constant declarations>>
// Pass SQL string to the query() method
await client.query(sqlString, sqlValues, function(err, result) {
<< Insert If-Else Condition 1 Here >>
<< Insert If-Else Condition 2 Here >>
if (someCondition == 1) {
// Rollback before executing another transaction
client.query("ROLLBACK");
} else if (err) {
client.query("ROLLBACK");
res.status(500).send("Server Error");
} else {
client.query("COMMIT");
res.json({ "message": "done!" });
}
});
} catch (er) {
// Rollback before executing another transaction
client.query("ROLLBACK");
}
} finally {
client.release();
}
execute();
上面的代码是有效的,虽然我想在事务中放置两个 if-else 条件块,如果条件满足,它将触发 2 个查询,如果是真或假,将继续if (someCondition == 1) 条件块。
这是我想提出的两个 if-else 条件:
if (conditionA == true) {
await pool.query(query1)
}
if (conditionB == true) {
await pool.query(query2)
}
运行它们会导致错误:
SyntaxError: await is only valid in async function,原点在await pool.query(query1)。
删除 await 会导致未解决的承诺错误。
我不知道如何做这部分。我一直在通过保存点修补嵌套事务,但无济于事。
谢谢你!
【问题讨论】:
-
只放入你用 if-else 编写的代码有什么问题?
-
只需将您的陈述准确地放在您放置 cmets 的位置即可。记住交易是如何运作的。事务从第一个 DML 语句开始或在显式开始时开始。您使用 client.query("BEGIN"); 显式启动了一个事务;一旦一个事务启动,一切(至少是数据库调用)都是其中的一部分,直到发出提交或回滚。注意:如果它在您的应用或 IDE 中可用,请确保它已关闭。
-
@bobflux 我有一个错误,说我只能在异步函数中使用 await,我觉得这很奇怪,因为整个事务都是异步的,除非我遗漏了什么?
-
@Belayer 是的,我打算这样(如果我对您的理解正确的话)要么全部进入,要么没有进入(不是确切的术语,但同样的想法),因为我希望查询是原子的以保持一致性。
-
@vitaly-t 是的,我刚刚做到了。值得反思的一天,但对于 tx 和任务的工作方式,这是值得的。绝对是救命稻草!
标签: node.js postgresql node-postgres