總之,使用交易:
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.all
的操作失敗,交易將被回滾。