在indexedDB中打开多个数据库连接是不是很糟糕?

Gar*_*nzo 5 jquery indexeddb

我一直在使用IndexedDB,我可以成功创建一个新数据库,创建一个商店,并在"需要升级时"添加一个值.我不明白的是,数据库是否保持"开放"状态,还是必须在需要访问数据库中读/写信息的每个函数内重新打开它?

例如,这是我的代码(可以工作)来创建一个新数据库,并插入一条记录:

$(document).ready(function() {

var db;

function initDB() {
    console.log("opening db...");

    var req = indexedDB.open(dbName, version);
    req.onsuccess = function(event) {
      db = this.result;
      console.log("opening db is done");
    }

    req.onerror = function(event) {
      console.log("error opening db: ", event.target.errorCode);
    }

    req.onupgradeneeded = function(event) {
      db = event.target.result;
      var store = db.createObjectStore("creds", { autoincrement: true });
      store.add({ username:'none', password:'none'}, 1);
    }
  }
Run Code Online (Sandbox Code Playgroud)

造成我混淆的是,当我需要访问该数据库中的记录,或添加更多记录或删除记录时,我想我可以创建一个新函数并插入一些值.这就是我所拥有的(失败):

  function saveCreds() {
    usr = $("#username").val();
    psw = $("#password").val();

    $.getJSON(baseURL + "cred-check/?callback=?", { username:usr, password:psw }, function(data) {
      if (data.creds_good == 'true'); {
        // NEXT LINE FAILS
        var store = db.transaction(['creds'], 'readwrite').objectStore('creds');
        var request = store.get(1);
        request.onsuccess = function (event) {
          var data = request.result;
          data.username = usr;
          data.password = psw;

          var requestUpdate = store.put(data, 1);
          requestUpdate.onerror = function(event) {
            console.log("error putting value...");
          }
        }
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

saveCredsinitDB函数是内部$(document).ready()函数和db变量声明之外initDBsaveCreds功能,但里面$(document).ready(),所以我觉得我的范围是确定的.

问题是,db变量未定义.我收到错误:Cannot call method "transaction" of undefined.

这是否意味着对于需要访问数据库中的数据的每个函数,我需要重新打开它,并将其重新分配给变量,以便我可以操作/读取数据库中的数据?

Jos*_*osh 5

我的回答一定是:有时。不,您不需要总是打开新连接。您可以在一个连接上使用多个事务。执行此操作的一个简单方法是将 db 变量传递给这些函数。但是,您必须了解 javascript 以及 indexedDB 的异步特性。有时您需要打开一个新连接。例如,在某些其他事件的触发时。

因此,如果您正在进行多个事务,请使用如下所示的大型函数:

function domultiplethings() {
  var db = ... 
  callfunction1(db);
  callfunction2(db);
}

function callfunction1(db) {
  if(!db) {
    // open a new connection then call ourself
  } else {
    // active connection, do read/write stuff
  }
}
Run Code Online (Sandbox Code Playgroud)