2017-03-18 25 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}); 

トランザクションはオプションオブジェクトの一部です。エラーが発生した場合

await sequelize.transaction(async t=>{ 
    const user = User.create({ name: "Alex", pwd: "2dwe3dcd" }, { transaction: t}) 
    const group = Group.findOne({ name: "Admins", transaction: t}) 
    // etc. 
}) 

は、取引がされています

+1

上記の答えを修正しました - ありがとう – pkyeck

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); 
} 
関連する問題