与 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/