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

node.js sequelize transaction using array for queries

我想将更新放在事务中的 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
    });
});