首页 > 解决方案 > 如何在 Sequelize 中使用带有函数调用的事务

问题描述

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

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

我目前正在将事务作为函数调用中的参数传递。

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

标签: node.jsfunctiontransactionssequelize.js

解决方案


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

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


推荐阅读