【问题标题】:node.js sequelize transaction using array for queriesnode.js 使用数组查询后续事务
【发布时间】:2021-03-09 20:10:51
【问题描述】:

我想将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
});

有可能吗?如果有,怎么做?

【问题讨论】:

    标签: node.js typescript sequelize.js


    【解决方案1】:

    最好把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
        });
    });
    

    【讨论】:

    • 我认为这更像是一个建议/提议,而不是一个实际的答案。我会给你一个赞成票,但这并不能解决我的问题
    • 据我了解,您希望在同一事务中进行多项更改。如果不是,请在您的问题中澄清一下您想要实现的目标
    • 我想使用data.clothes 数组进行事务内部的查询
    • 我在答案中添加了一个带循环的示例
    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 2017-08-09
    • 2016-01-24
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多