后提交 hook

transaction 对象允许跟踪是否提交以及何时提交.

可以将 afterCommit hook 添加到托管和非托管事务对象:

  1. sequelize.transaction(t => {
  2. t.afterCommit((transaction) => {
  3. // 你的逻辑片段
  4. });
  5. });
  6. sequelize.transaction().then(t => {
  7. t.afterCommit((transaction) => {
  8. // 你的逻辑片段
  9. });
  10. return t.commit();
  11. })

传递给 afterCommit 的函数可以有选择地返回一个 promise,在创建事务的 promise 链解析之前这个 promise 会被解析.

afterCommit 如果事务回滚,hook 不会 被提升.

afterCommit hook 不像标准 hook, 不会 修改事务的返回值.

你可以将 afterCommit hook 与模型 hook 结合使用,以了解实例何时在事务外保存并可用

  1. model.afterSave((instance, options) => {
  2. if (options.transaction) {
  3. // 在事务内保存完成,等到事务被提交以通知监听器实例已被保存
  4. options.transaction.afterCommit(() => /* Notify */)
  5. return;
  6. }
  7. // 在事务之外保存完成,对于调用者来说可以安全地获取更新后的模型通知
  8. })