2017-03-18 217 views

回答

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(); 
} 
+0

這是行不通的。在這種情況下't'是一個Promise而不是交易對象。 – Pier

+1

@Pier,等待sequelize.transaction()然後得到它的結果。 t不是承諾,而是承諾的結果。 –

+0

哦,你是對的,我完全錯過了 – Pier

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

接受的答案是一個「非託管交易」,它要求您明確地呼叫commitrollback。誰想要一個「管理交易」,這是它會是什麼樣子:

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); 
} 
相關問題