1

当我查看交易文档时,我遇到了这个例子:

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变量根本没有改变值。

4

1 回答 1

1

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

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

此外,在您的示例中,您不会等待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:我会联系开发团队更新示例

于 2018-01-18T15:38:19.597 回答