【发布时间】:2019-06-29 08:38:54
【问题描述】:
我有类似下面的代码:
const _addEvents = async(eventList, day, transaction) => {
await eventList.forEach(event => {
return model.events.findOne({where:event, transaction: transaction}).then(event => {
if(!event) {
transaction.rollback();
throw new Error("event not found");
}
return event;
})
.then(event => {
day.addEvents(event, {through: {status: 'ENABLED'}});
day.save();
})
})
}
}
export const create = async(attributes) => {
return await sequelize.transaction(async(t) => {
return model.days.create(attributes, {transaction: t})).then(async(day) => {
await _addEvents(attributes.eventList, day, t);
return day;
})
})
}
我看到的是交易开始,并且在交易中的天数中添加了一行。在第一次迭代中,当在方法 _addEvents 中调用 findOne 时,事务被提交。
我使用了Sequelize.useCLS("foo");,所以我希望所有事务都在同一个命名空间中但是我传递事务只是为了确定。
谁能告诉我为什么事务在findOne 执行后提交,并告诉我如何避免这种情况发生。
我正在使用 (babel-core 6.26.3) 和 node.js v9.2.0 和 postgres 10.5
【问题讨论】:
标签: node.js transactions sequelize.js