我正在尝试使用node.js 在 Neo4j 数据库中创建一些 Node 和连接。我正在摆弄一些教程并尝试修改它们。我是 Node 菜鸟。在这种情况下,我有一个正在解析的对象数组以填充数据库。每个对象内都有经验
数组。我不断收到错误;
Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
我认为该错误与循环experiences.forEach
有关。这是循环中的循环。我不知道如何克服这个问题。
// Create a person node
function addPerson(tx, name) {
return tx.run("MERGE (a:Person {name: $name})", { name: name });
}
// Create a position node
async function addPosition(tx, name) {
return tx.run("CREATE (a:Position {name: $name})", { name: name });
}
// Create an employment relationship to a pre-existing Person node.
// This relies on the person first having been created.
function addPositionConnection(tx, personName, positionTitle) {
return tx.run(
"MATCH (person:Person {name: $personName}) " + "MATCH (position:Position {name: $positionTitle}) " + "CREATE (person)-[:HAS_POSITION]->(position)",
{
personName: personName,
positionTitle: positionTitle
}
);
}
(async function neo4jInsertData() {
try {
const profiles = [
{
userProfile: {
fullName: "Test name 1"
},
experiences: [
{
title: "CEO"
}
]
},
{
userProfile: {
fullName: "Test name 2"
},
experiences: [
{
title: "CTO"
}
]
}
];
for (var x = 0; x < profiles.length; x++) {
const name = profiles[x].userProfile.fullName;
const experiences = profiles[x].experiences;
const session1 = driver.session(neo4j.WRITE);
const first = session1
.writeTransaction(tx => addPerson(tx, name))
.then(tx => {
try {
experiences.forEach((tx, experience, index) => {
addPosition(tx, experience.title).then(() => addPositionConnection(tx, name, experience.title));
});
} catch (err) {
console.log("err", err);
}
})
.then(() => {
console.log("closing");
return session1.close();
});
}
} catch (err) {
console.log("there is an error", err);
}
})();
最佳答案
您的 addPosition
函数用 async
注释,因此 addPosition
将返回一个可能被异步拒绝的 Promise(例如,如果其 >tx.run
调用抛出异常)。
您收到的错误消息表明您的 addPosition
调用(具有 then
block )返回的 Promise 被拒绝,但由于 Promise 没有 catch
阻止无法处理拒绝。
解决此问题的一种方法是使用 await
注释 addPosition
调用,这会将任何 promise 拒绝转换为引发的异常。
关于javascript - Neo4j 与 Node.js 在数组中插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59557004/