transactions - 可以在前端显示sql事务运行状态吗

标签 transactions sequelize.js

Sequelize交易,https://sequelize.org/master/manual/transactions.html ,

try {

  const result = 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 });

    return user;

  });

  // If the execution reaches this line, the transaction has been committed successfully
  // `result` is whatever was returned from the transaction callback (the `user`, in this case)

} catch (error) {

  // If the execution reaches this line, an error occurred.
  // The transaction has already been rolled back automatically by Sequelize!

}
是否可以在前端显示事务运行状态?例如,在运行 setShooter 之前User.create 上还没有错误,在前端,我会显示creating a user创建用户后,我会显示setting shooter在前端。

最佳答案

笔记:
您将需要在客户端上实现一个加载器,该加载器将等待 afterCommit 调用并在事务后执行逻辑期间显示您想要的消息。
事务对象允许跟踪它是否以及何时提交。
afterCommit 钩子(Hook)可以添加到托管和非托管事务对象中:
托管交易:

await sequelize.transaction(async (t) => {
  t.afterCommit(() => {
    // Your logic
  });
});
非托管事务:
const t = await sequelize.transaction();
t.afterCommit(() => {
  // Your logic
});
await t.commit();
传递给 afterCommit 的回调可以是异步的。在这种情况下:sequelize.transaction call 将在解决之前等待它;t.commit call 将在解决之前等待它。
如果事务回滚,则不会引发 afterCommit 钩子(Hook);
afterCommit 钩子(Hook)不会修改事务的返回值
您可以将 afterCommit 钩子(Hook)与模型钩子(Hook)结合使用,以了解实例何时被保存并在事务之外可用
User.afterSave((instance, options) => {
  if (options.transaction) {
    // Save done within a transaction, wait until transaction is committed to
    // notify listeners the instance has been saved
    options.transaction.afterCommit(() => /* Notify */)
    return;
  }
  // Save done outside a transaction, safe for callers to fetch the updated model
  // Notify
});

关于transactions - 可以在前端显示sql事务运行状态吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67667013/

相关文章:

ruby-on-rails - 错误 : current transaction is aborted, 命令被忽略,直到事务 block 结束,Ruby on Rails

node.js - 使用 sequelize 和 typescript 自动迁移

Mongodb/嵌套事务: open transaction in another one not working

postgresql - 将 postgreSQL 存储过程作为一个事务执行

sql - 在 PostgreSQL 事务 block 中获取 ID

sequelize.js - Node JS Sequelize,如何在迁移时同步更改模型

node.js - Sequelize : Only returning one of many result for a nested include

javascript - Sequelize 无法创建表,但是当我在 MySQL CLI 中运行它时它可以工作

node.js - 在 SQLite 中插入数据值的同步循环

mysql - XA恢复: how to convert unreadable xid