Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
02-20-2021 10:18 AM
I cannot find any definitely working examples online of running multiple queries inside a single transaction using JavaScript without using "await".
The closest thing I have is the following:
const tx = session.beginTransaction();
tx.run("CREATE (p:Person { name: $name })", { name: "Adam" })
.then(res => {
// Run another query with the tx variable...
})
.then(() => {
// Everything is OK, the transaction will be committed
})
.catch(e => {
// The transaction will be rolled back, now handle the error.
});
However, I can't figure out how to write in a second query.
I'd be grateful for any help.
Thank you.
02-20-2021 07:31 PM
I need the example too.
I rummaged through all the documents, but I can't find the result.
03-02-2021 04:48 AM
Can anyone from Neo4j weigh in on this?
03-02-2021 06:33 AM
Hi,
you could run N queries like:
const result1 = tx.run('RETURN 1')
const result2 = tx.run('RETURN 2')
.
.
.
const resultN = tx.run('...')
And then consuming the result as a promise, or calling the subscribe
method.
Important to notice the queries will only be sent to the server when it the result start to be consumed. So, the usage of the method Promise.all
could helpful in your case.
Thanks
03-02-2021 11:29 AM
Thank you for replying
What do I do if the nature of my second query depends on the result of the first query?
How do I send a query, process the result, and then send another query all in the same transaction?
03-03-2021 01:57 AM
Then you should consume the result as you did in your example, with the dependent query being run inside in the then
(or after an await
, if you prefer). We don't have a sync API to run queries in JS.
03-04-2021 03:44 AM
Would something like this work?
const neo4j = require('neo4j-driver')
const uri = "neo4j://localhost"
const user = "neo4j"
const password = "neo"
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session()
const personName = 'Alice'
const tx = session.beginTransaction();
tx.run('CREATE (a:Person {name: $name}) RETURN a', { name: personName }).then(result => {
let person1Name
result.records.forEach(record => {
person1Name = record.get('a').properties["name"]
})
return tx.run('CRaEATE (b:Person {name: $name}) RETURN b', {name: person1Name + "2"})
}).then(result => {
result.records.forEach(record => {
console.log(record)
})
return tx.commit()
}).then(() => {
session.close()
driver.close()
}).catch(exception => {
console.log(exception)
session.close()
driver.close()
})
I have a deliberate typo in the 2nd query so that it throws an exception and doesn't commit the transaction.
All the sessions of the conference are now available online