【发布时间】:2022-02-06 03:08:09
【问题描述】:
我正在尝试使用 bluebird 和 sqlite3 构建一个数据库来管理很多“成分”。 到目前为止,我已经成功地解析了一个文件并使用正则表达式从中推断出一些数据。
每次一行匹配正则表达式时,我想在数据库中搜索是否已经插入了同名的元素,如果是,则跳过该元素,否则必须插入。 问题是某些元素被多次插入。 代码部分有效,我说它部分有效,因为如果我删除检查是否存在同名元素的代码行,重复的行会更多。 p>
这是一段代码:
lineReader.eachLine(FILE_NAME, (line, last, cb) => {
let match = regex.exec(line);
if (match != null) {
let matchedName = match[1].trim();
//This function return a Promise for all the rows with corresponding name
ingredientsRepo.getByName(matchedName)
.then((entries) => {
if (entries.length > 0) {
console.log("ALREADY INSERTED INGREDIENT: " + matchedName)
} else {
console.log("ADDING " + matchedName)
ingredientsRepo.create(matchedName)
}
})
}
});
我知道我遗漏了一些关于 Promises 的内容,但我不明白我做错了什么。
这是getByName(name) 和create(name) 的代码:
create(name) {
return this.dao.run(
`INSERT INTO ingredients (name) VALUES (?)`,
[name]
)
}
getByName(name) {
return this.dao.all(
'SELECT * FROM ingredients WHERE name == ?',
[name]
)
}
【问题讨论】:
标签: node.js sqlite promise bluebird