[英]TypeORM transaction saving entity to database despite the next transaction step failing
我想进行交易以保存新表行和该行的多对多帮助器表条目。 我使用同一个事务管理器来保存这两个文件,但是当第二部分失败时,第一部分不会恢复。 为什么会这样呢?
await getManager().transaction(async transactionalEntityManager => {
newFeed = await transactionalEntityManager
.createQueryBuilder()
.insert()
.into(Feed)
.values({ ...feed })
.execute();
console.log('======================================\n', newFeed);
feed.sources.forEach(async source => {
console.log('==in forEach===\n', source.id, newFeed.identifiers[0].id);
await transactionalEntityManager
.createQueryBuilder()
.insert()
.into('feed_source')
.values({
sourceId: source.id,
feedId: newFeed.identifiers[0].id,
fontColor: feed.fontColor ? feed.fontColor : null,
postColor: feed.postColor ? feed.postColor : null
})
.execute();
});
});
与语法有关吗? 我以前没有使用过插入查询生成器语法。 .execute()是否会忽略事务? 这样做的正确方法是什么?
好的,我解决了。 原因是forEach似乎是异步行为,因此代码会在完成循环之前跳到事务结束。 在寻找解决方案时,我更改了所用的方法和某些功能,因此代码最终变得完全不同,但是主要的事情是我使用了Promise.all()并将返回的.map()结果传递给它承诺。
await getManager().transaction(async transactionalEntityManager => {
savedFeed = await transactionalEntityManager.save(newFeed);
if (feed.feedSources) {
newFeed.feedSources = [];
await Promise.all(
feed.feedSources.map(async feedSource => {
return new Promise(async (resolve, reject) => {
const referencedSource = await Source.findOne(feedSource.sourceId);
console.log('===referencedSource===\n', referencedSource);
if (!referencedSource)
throw new Error(
'Could not find referenced source with id ' + feedSource.id
);
const currentFeedSource = new FeedSource();
currentFeedSource.source = referencedSource;
currentFeedSource.feed = savedFeed;
feedSource.postColor
? (currentFeedSource.postColor = feedSource.postColor)
: '';
feedSource.fontColor
? (currentFeedSource.fontColor = feedSource.fontColor)
: '';
console.log('===currentFeedSource===\n', currentFeedSource);
await transactionalEntityManager.save(currentFeedSource);
resolve(true);
});
})
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.