Node.js 7已经支持async/await语法,在sequelize事务中如果使用async/await会导致事务未启用,应该如何使用?Node.js 7如何使用async/await进行sequelize事务?
8
A
回答
21
let transaction;
try {
// get transaction
transaction = await sequelize.transaction();
// step 1
await Model.destroy({where: {id}, transaction});
// step 2
await Model.create({}, {transaction});
// commit
await transaction.commit();
} catch (err) {
// Rollback transaction if any errors were encountered
await transaction.rollback();
}
3
上述代码在销毁调用中有错误。
await Model.destroy({where: {id}, transaction});
交易是选项对象的一部分。
+1
修正了上面的答案 - 谢谢 – pkyeck
1
通过user7403683给出的答案描述异步/ AWAIT方式对非托管交易(http://docs.sequelizejs.com/manual/tutorial/transactions.html#unmanaged-transaction-then-callback-)
管理的事务在异步/等待风格可能会是这样:
await sequelize.transaction(async t=>{
const user = User.create({ name: "Alex", pwd: "2dwe3dcd" }, { transaction: t})
const group = Group.findOne({ name: "Admins", transaction: t})
// etc.
})
如果发生错误,交易自动回滚。
0
接受的答案是一个“非托管交易”,它要求您明确地呼叫commit
和rollback
。谁想要一个“管理交易”,这是它会是什么样子:
try {
// Result is whatever you returned inside the transaction
let result = await sequelize.transaction(async (transaction) => {
// step 1
await Model.destroy({where: {id}, transaction});
// step 2
return await Model.create({}, {transaction});
});
// In this case, an instance of Model
console.log(result);
} catch (err) {
// Rollback transaction if any errors were encountered
console.log(err);
}
要回滚,只是抛出一个错误的事务函数内:
try {
// Result is whatever you returned inside the transaction
let result = await sequelize.transaction(async (transaction) => {
// step 1
await Model.destroy({where: {id}, transaction});
// Cause rollback
if(false){
throw new Error('Rollback initiated');
}
// step 2
return await Model.create({}, {transaction});
});
// In this case, an instance of Model
console.log(result);
} catch (err) {
// Rollback transaction if any errors were encountered
console.log(err);
}
这是行不通的。在这种情况下't'是一个Promise而不是交易对象。 – Pier
@Pier,等待sequelize.transaction()然后得到它的结果。 t不是承诺,而是承诺的结果。 –
哦,你是对的,我完全错过了 – Pier