omega
omega

Reputation: 43843

Better way to handle connections for indexed db api?

I am using the html5 indexed db api to store cache, but I constantly get errors about connection being blocked when I try to delete the database. I realized later that it is probably because I don't explicitly close the connections. What I do is just open it, and store the database variable in a global variable, then just use that and never close it.

But now I think I have two options for how to handle it but not sure which is the better one. In my app, there will be lots of times reading and writing to the database, and it can happen at same time.

So my two approaches are

1) For every time I read or write, I open the database into a new variable, and after completing the task, I close it.

2) Only open it when I write or read and if it is not already opened, then after you finish it, close only if nothing else is using it. If something else is, then keep it open, because that other thing will close it.

Does anyone know if one of these will work better?

Thanks

Upvotes: 0

Views: 278

Answers (2)

Joshua Bell
Joshua Bell

Reputation: 8337

Another unstated option is to listen for "versionchange" events fired at the connection and close the connection in response to unblock the deletes.

var connection;

var open = indexedDB.open(name, version);
open.onupgradeneeded = function() {
  // populate schema here
};
open.onsuccess = function() {
  connection = open.result;
  connection.onversionchange = function(e) {
    if (e.newVersion === 0)
      console.log('being deleted');
    else
      console.log('being upgraded');

    connection.close();
    connection = null; // so other code can tell it is closed
  };
};

Upvotes: 1

Josh
Josh

Reputation: 18690

I like to open and close every time. The answer is subjective.

Upvotes: 0

Related Questions