cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Need examples of running multiple queries in a single transaction using JavaScript without using "await"

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.
    });

From: Using the Neo4j Driver with NodeJS - Adam Cowley | Full Stack Development Lead specialising in Neo4j...

However, I can't figure out how to write in a second query.

I'd be grateful for any help.

Thank you.

6 REPLIES 6

I need the example too.
I rummaged through all the documents, but I can't find the result.

Can anyone from Neo4j weigh in on this?

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

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?

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.

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.