遍历 Neo4j 入门 Node.js 代码

Walking through Neo4j starter Node.js code

我对 node.js 和 neo4j 都很陌生(这是我第一次构建后端)所以我对 node.js 的 neo4j 起始代码的某些部分感到困惑。

  1. 为什么包括导入在内的所有内容都需要在异步箭头函数中?我不是 async/await 方面的专家,但导入需要在其中似乎很奇怪。

  2. 在我的后端 运行 不间断的情况下,我永远不会关闭驱动程序吗?但我会关闭会话?有没有简单的方法来解释这两个实体之间的区别?

node.js 的 Neo4j 起始代码:

(async() => {
    const neo4j = require('neo4j-driver')

    const uri = "uri";
    const user = "user";
    const password = "password";

    const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
    const session = driver.session()

    const person1Name = 'Alice'
    const person2Name = 'David'

    try {
        // To learn more about the Cypher syntax, see https://neo4j.com/docs/cypher-manual/current/
        // The Reference Card is also a good resource for keywords https://neo4j.com/docs/cypher-refcard/current/
        const writeQuery = `MERGE (p1:Person { name: $person1Name })
                       MERGE (p2:Person { name: $person2Name })
                       MERGE (p1)-[:KNOWS]->(p2)
                       RETURN p1, p2`

        // Write transactions allow the driver to handle retries and transient errors
        const writeResult = await session.writeTransaction(tx =>
            tx.run(writeQuery, { person1Name, person2Name })
        )
        writeResult.records.forEach(record => {
            const person1Node = record.get('p1')
            const person2Node = record.get('p2')
            console.log(
                `Created friendship between: ${person1Node.properties.name}, ${person2Node.properties.name}`
            )
        })

        const readQuery = `MATCH (p:Person)
                      WHERE p.name = $personName
                      RETURN p.name AS name`
        const readResult = await session.readTransaction(tx =>
            tx.run(readQuery, { personName: person1Name })
        )
        readResult.records.forEach(record => {
            console.log(`Found person: ${record.get('name')}`)
        })
    } catch (error) {
        console.error('Something went wrong: ', error)
    } finally {
        await session.close()
    }

    // Don't forget to close the driver connection when you're finished with it
    await driver.close()
})();

请注意,这会引发错误,因为出于显而易见的原因,我没有透露用户名和密码。

Why does everything, including the imports, need to be inside an async arrow function? I am not an expert on async/await but it seems weird that imports would need to be inside that.

当然,它们不需要在异步内部,据我所知,这是最简单的示例来展示处理 neo4j 连接所需的确切内容。也许值得检查更广泛的例子,例如here

In a context where my back-end is running non-stop, would I never close the driver? But I would close sessions? Is there a simple way to explain the difference between these two entities?

neo4j 文档中似乎对所有内容都有很好的描述:

此外,值得花一些时间来理解驱动程序、会话和事务的概念,因为它对所有数据库(关系型和非关系型)都很常见。