javascript - 我收到错误:在 else 语句中查询已释放或丢失的连接
问题描述
这是代码,我正在尝试检查插入语句的结果。如果它为null(如果标签标题已经存在),它必须执行else语句。但它在 else 语句中失败,抛出丢失的连接错误。
return this.store.tx('create-tags', async (transaction: any) => {
tagDetails.forEach((tag: any) => {
transaction
.oneOrNone(
`INSERT INTO tag(title)
VALUES ($1)
ON CONFLICT DO NOTHING
RETURNING tag_id, title`,
[tag.title],
)
.then((result: any) => {
console.log('the tag details are', result);
if (result !== null) {
this.createTags(collectionId, tag.item_id, result.tag_id);
} else {
transaction.oneOrNone(
`
SELECT tag_id
FROM tag
WHERE title = $1
`,
[tag.title],
).then((tagId: string) => {
console.log('the tagid in else statement is', tagId);
if (tagId) {
this.createTags(collectionId, tag.item_id, tagId);
}
})
.catch(err => {
console.log('the error in else statement is', err);
});
}
});
});
解决方案
您的代码显示了许多问题。
主要的,也是您收到错误的原因,是因为您未能将查询结果链接到事务结果中。您最终会尝试在事务上下文之外执行多个查询,因此会出现错误。这是一个修改后的版本,可以解决这个问题:
return this.store.tx('create-tags', t => {
const res = tagDetails.map((tag: any) => {
return t.oneOrNone(`INSERT INTO tag(title) VALUES ($1) ON CONFLICT DO NOTHING RETURNING tag_id, title`,
[tag.title],
)
.then((result: any) => {
console.log('the tag details are', result);
if (result !== null) {
return this.createTags(collectionId, tag.item_id, result.tag_id);
} else {
return t.oneOrNone(`SELECT tag_id FROM tag WHERE title = $1`, [tag.title])
.then((tagId: string) => {
console.log('the tagid in else statement is', tagId);
if (tagId) {
return this.createTags(collectionId, tag.item_id, tagId);
}
})
.catch(err => {
console.log('the error in else statement is', err);
});
}
});
});
return t.batch(res);
});
但是,这并不是特别好,原因如下:
- 您应该使用完整的
async
代码重写它 - 您应该在事务之外进行错误处理
- 您的整个代码看起来可以只用一个查询替换。
- 我们不知道是什么
createTags
,因此无法对此发表评论
推荐阅读
- javascript - 即使包裹在 Number() 中,JavaScript 函数也会返回 NaN?
- delphi - 如何找出 tmemo 组件中的字符数?
- python - 滑累计和python
- python - Python将字符串列表减少为int
- makefile - 是否可以将延迟评估的变量导出到子 Makefile?
- python - ValueError:无法将字符串转换为浮点小数
- android - 我可以在我的 android 应用程序代码中登录谷歌帐户吗?
- java - docker tomcat启动后运行命令
- spring-boot - 找不到依赖项 'com.h2database:h2:1.4.200',无法读取 com.h2database:h2:jar 的工件描述符
- vuejs2 - 在每个路由之前验证访问 jwt 令牌,如果无效,则在 vue-cli 中注销