简而言之,使用事务:
sequelize.transaction().then(function (t) {
return sequelize.Promise.all([
Project.create({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
}, { transaction: t }),
Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
}, { transaction: t })
]).then(function onFulfilled (project, task) {
return t.commit();
}, function onRejected(err) {
return t.rollback();
});
});
在最新版本(2.0-rc2)中,这也可以更简洁地写成:
sequelize.transaction(function (t) {
return sequelize.Promise.all([
Project.create({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
}, { transaction: t }),
Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
}, { transaction: t })
]);
});
通过将回调传递给transaction 而不是调用then。回调返回一个promsie链,事务是提交还是回滚,取决于返回的promise是否成功。这意味着如果传递给Promise.all 的任何操作失败,事务将被回滚。