node.js - 如何在 Sequelize 中使用带有函数调用的事务
问题描述
我正在使用 Sequelize 交易。我想了解当我们进行函数调用时如何处理事务,并且在被调用的函数中我们执行更多事务。
如果出现任何问题,应回滚所有事务,包括被调用函数中的事务。
我目前正在将事务作为函数调用中的参数传递。
这是正确的方式吗?我在 Sequelize 文档中也找不到与之相关的任何内容。
解决方案
只要您在调用函数的任何位置从该函数捕获错误,将事务传递给函数应该可以正常工作,这样您就可以在必要时回滚事务。
const helperFunction(transaction) {
// do something with transaction here
// do NOT catch error here
// No need to return Transaction
}
async function main() {
let transaction;
try {
transaction = await sequelize.transaction();
await helperFunction(transaction);
await transaction.commit();
} catch(err) {
if (transaction) await transaction.rollback();
// continue handling error
}
}
您也可以只在我们的事务范围内定义这些函数,这样您就不必传递它。例如:
async function main() {
let transaction;
const helperFunction() {
// do something with transaction here
// do NOT catch error here
}
try {
transaction = await sequelize.transaction();
await helperFunction();
await transaction.commit();
} catch(err) {
if (transaction) await transaction.rollback();
// continue handling error
}
}
推荐阅读
- c# - C# - 列表视图按前缀图标而不是文本排序
- r - 如何设置符号和颜色以区分 R 图中的数据?
- javascript - FireStore - LimitToLast 不是函数
- javascript - 如何在返回和第四次导航到页面时让结果页面与关键字保持一致?
- html - CSS无论如何都没有加载
- git - 我希望我的文件保留在我的 git 存储库中,但我不希望任何人能够更改或提交更改
- python - pythonic从字符串中识别和删除子字符串的方法
- postgresql - 基于多列按日期时间获取最后一条记录
- ruby-on-rails - Rails Fast Json API 包括范围
- c++ - Windows 应用程序是否支持用户定义的信号处理程序的 SIGINT?