Reputation: 39
sequelize transaction not rolling back when I use Promise.all with "looping update"
I'm using PostgreSQL with sequelize and the code below works fine if there is no error.
return db.transaction(t => {
let promises = [];
promises.push(
valuesToUpdate.map(item => {
return db.models.TableToUpdate.update(
{
prop1: item.val1,
prop2: item.val2,
prop3: item.val3,
prop4: item.val4
}
);
})
);
return Promise.all(promises)
.then(res => {
return h.response().code(201);
})
.catch(err => {
console.log(err);
});
});
Expected result: When there is an error in any of the updated values, sequelize should roll back everything in that transaction
Actual result: When there is an error in any of the updated values, sequelize commits correct values, but does not commit values with error (like not null violation, etc.). I don't want this. Also if there is an error, the catch block is invoked, but sequelize still does not roll back.
Upvotes: 0
Views: 2523
Reputation: 1968
There needs to be a catch at the transaction level. Here's the structure I use:
sequelizeDB.transaction(function (t) {
...
promises.push(newPromise1);
...
promises.push(newPromise2);
...
return Promise.all(promises);
}).then(function () {
console.log("SUCCESS!!! (will commit)");
next();
}).catch(function (err) {
console.log("FAILURE !!! (will rollback)");
return next(err);
});
Upvotes: 1