PONPON
(Kobayashi Takanori)
March 24, 2020, 5:29am
1
If I run this example (JavaScript), I get the following error:
const result = await session.writeTransaction(tx =>
^^^^^
SyntaxError: await is only valid in async function
My code is as follows:
const uri = 'bolt://my.ip.add.ress:7687'
const user = 'neo4j'
const password = 'neo4j'
const neo4j = require('neo4j-driver')
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
try {
const result = await session.writeTransaction(tx =>
tx.run(
'CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)',
{ message: 'hello, world' }
)
)
const singleRecord = result.records[0]
const greeting = singleRecord.get(0)
console.log(greeting)
} finally {
await session.close()
}
// on application exit:
await driver.close()
What should I do?
What version of the driver are you using? The example you're quoting from is from the 4.0 driver examples. If you switch to the 1.7 driver examples, you won't see await
in the code.
PONPON
(Kobayashi Takanori)
March 25, 2020, 12:22am
3
I am using version 4.0.2.
The error you're seeing is a basic javascript error saying that the await keyword doesn't work outside of the context of an async function.
Try this, and it should work:
async function main() {
try {
const result = await session.writeTransaction(tx =>
tx.run(
'CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)',
{ message: 'hello, world' }
)
)
const singleRecord = result.records[0]
const greeting = singleRecord.get(0)
console.log(greeting)
} finally {
await session.close()
}
// on application exit:
await driver.close()
}
main();
You'll notice that all I did was wrap your code in async function main() and then called that async function at the bottom. The result should work, because you are no longer using "await" outside of an async function.
More information on how async/await works is right here, which includes the disclaimer: