node.js 使用数组对事务进行 Sequelize 进行查询

标签 node.js typescript sequelize.js

我想将 clothingModel 上的更新放在事务中,如果它提交,则更新 reservationModel
这是我尝试使用 sequelize.transaction 重写的代码

    try {
      data.clothes.forEach(async (clothing) => {
        await this.clothingModel.update(
          { price: clothing.price },
          { where: { id: clothing.clothingId } }
        );
      });
    } catch (e) {
      //throw exception
    }
    //if exception is not thrown
    this.reservationModel.update(
      { dropoffStatus: 'APPROVED' },
      { where: { id: data.reservationId } }
    );
但是我一直在努力使其符合 sequelize 中使用事务的方式
sequelize.transaction(function (t) {
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(function (user) {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });
}).then(function (result) {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback 
}).catch(function (err) {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});
是否可以?如果是这样,如何?

最佳答案

最好将 transaction 回调转换为 async 使其看起来像顺序代码:

try {
  const createdUser = await sequelize.transaction(async t => {
    const user = await User.create({
      firstName: 'Abraham',
      lastName: 'Lincoln'
    }, {transaction: t});
    await user.setShooter({
        firstName: 'John',
        lastName: 'Boothe'
      }, {transaction: t});
    })
  });
  // transaction committed
  .. other code
} catch (err) {
  // transaction rolled back
}
循环的附加示例:
await sequelize.transaction(async t => {
  for(const clothing of data.clothes) {
     await this.clothingModel.update(
       { price: clothing.price },
       { where: { id: clothing.clothingId },
         transaction: t
       }
     );
  }
  // you can move this `update` outside the callback
  // if you wish to execute it out of transaction
  this.reservationModel.update(
    { dropoffStatus: 'APPROVED' },
    { where: { id: data.reservationId },
      transaction: t
    });
});

关于node.js 使用数组对事务进行 Sequelize 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65030636/

相关文章:

javascript - Node 服务器关闭然后重新启动时的奇怪 socket.io 行为

angular - 订阅 promise

node.js - 在不同的微服务中序列化多对多表

node.js - 在mocha测试中调用异步函数如何避免超时错误: timeout of 2000ms exceeded

node.js - npm WARN 已弃用 minimatch@2.0.10 但我有更新的版本

node.js - 无法在截止日期前连接 URL :grpcs://localhost:8051

如果应用程序具有延迟加载功能,Angular 5 : Header, 页脚和侧边栏组件应该放在核心模块还是共享文件夹中?

Typescript类型的元组成员依赖于其他

sequelize.js - Sequelize 中查询结果的双重计数

mysql - 如何在 sequelize 的 sub-sub 子模型中添加条件,这会影响 findAndCountAll 中的父模型?