Friday, July 31, 2015

Close connections to your IndexedDB databases

Recently, I was attempting to run the deleteDatabase method of the IDBFactory interface of the IndexedDB API.  I noticed that occasionally the method would just hang there like it was stuck.  I slowly began to realize that it would hang if a connection was currently open.  This led me to researching how to close connections.

When you open a connection using the open method of IDBFactory, you get an object of type IDBDatabase.  In my experience, the only thing you do with the IDBDatabase object is to create the transaction object from it.  After you create the transaction, you should then immediately close the IDBDatabase object which closes the connection you opened.  At first, I wondered if you had to wait until you were done with the transaction before closing the connection, but apparently the close method knows to wait until all transactions created from it are completed.  This is from the specification:
Wait for all transactions created using connection to complete. Once they are complete, connection is closed.
Your code should look something like what is shown below. In this case, request is the IDBOpenDBRequest object.

request.onsuccess = function() {
    var db = event.target.result;

    var tx = db.transaction(['TableName'], 'readwrite');

    db.close();
}

No comments:

Post a Comment