【问题标题】:How to use Transactions with Functions Calls in Sequelize如何在 Sequelize 中使用带有函数调用的事务
【发布时间】:2021-07-14 15:26:55
【问题描述】:

我正在使用 Sequelize Transactions。我想了解当我们进行函数调用时如何处理事务,并且在被调用的函数中我们执行更多事务。

如果出现任何问题,所有事务,包括被调用函数中的事务都应该回滚。

我目前在函数调用中将交易作为参数传递。

这是正确的方法吗?我在 Sequelize 文档中也找不到与之相关的任何内容。

【问题讨论】:

    标签: node.js function transactions sequelize.js


    【解决方案1】:

    将事务传递给函数应该可以正常工作,只要您在调用函数的任何位置都从该函数中捕获错误,以便您可以在必要时回滚事务。

    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
         }
    }
    
    

    【讨论】:

    • 感谢您的帮助。我很感激你也给了第二个。我喜欢第二个。
    • 很高兴为您提供帮助!感谢您标记答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 2016-04-21
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多