Neo4j 事务误解

Neo4j transaction misunderstanding

当我查看 documentation for transactions 时,我偶然发现了这个例子:

var tx = session.beginTransaction();
tx.run("MERGE (bob:Person {name : {nameParam} }) RETURN bob.name AS name", {nameParam: 'Bob'})
  .subscribe({
    onNext: function (record) {
      console.log(record.get('name'));
    },
    onCompleted: function () {
      session.close();
    },
    onError: function (error) {
      console.log(error);
    }
  });

//decide if the transaction should be committed or rolled back
var success = false;

if (success) {
  tx.commit()
    .subscribe({
      onCompleted: function () {
        // this transaction is now committed 
      },
      onError: function (error) {
        console.log(error);
      }
    });
} else {
  //transaction is rolled black and nothing is created in the database
  console.log('rolled back');
  tx.rollback();
}

但是在上面的代码片段中它似乎并没有以某种方式改变 success 我的意思是它如何确定交易是否成功执行 success 变量根本没有改变值。

这是因为您在 onCompleted 回调函数上调用 session.close()

当您关闭一个会话时,它会自动提交所有底层打开的事务。

此外,在您的示例中,您没有等待 tx.run 承诺完成与否。你应该在 decide if the transaction should be committed or rolled back

部分进行

所以你应该这样做:

    var driver = neo4j.v1.driver("bolt://localhost",  neo4j.v1.auth.basic("neo4j", "neo4j"), { encrypted:false });
    var session = driver.session();
    // run statement in a transaction
    var tx = session.beginTransaction();
    tx.run("MERGE (bob:Person {name : {nameParam} }) RETURN bob.name AS name", {nameParam: 'Bob'})
      .subscribe({
        onNext: function (record) {
          console.log(record.get('name'));
        },
        onCompleted: function () {
          console.log('statement completed')
        },
        onError: function (error) {
          console.log(error);
        }
      });

    //decide if the transaction should be committed or rolled back
    var success = true;

    if (success) {
      tx.commit()
        .subscribe({
          onCompleted: function () {
            // this transaction is now committed 
          },
          onError: function (error) {
            console.log(error);
          }
        });
    } else {
      //transaction is rolled black and nothing is created in the database
      console.log('rolled back');
      tx.rollback();
    }
    session.close();

PS: 我会联系开发团队更新示例