The first statement opens a connection to a database called demo. It wants version 1. Fair enough. The second statement binds a function to the onupgradeneeded event on the connection. This fires when the database version is wrong or if the database is not there. The handler creates a new database called handles. So, if we ask for a database and it isn’t there, we make one. Lovely. The next statement creates a handler for the “happy path” - otherwise known as onsuccess. This is the code that runs once the database connection is open. When that happens we want to make an object called “folder” which contains the folder we created earlier. That’s what the transaction does. Now, when the website loads all my application has to do is look in the local database for the handle so it can use local files. Also lovely. All the code makes sense. So why did it make my head hurt?
Well, it’s because when I first looked at it I thought we were closing the stable door after the horse has bolted. The first statement does the open. And then, after that, we put the two event handlers in place to deal with what happens when the open runs. At first sight this seems wrong. How can the handlers get called when they aren’t set up at the time open runs? But it does makes sense. And it is all to do with how JavaScript in the browser does things.
The first thing you need to know is that indexedDB.open doesn’t open the database. It starts opening the database. So when open returns the database isn’t open. It’s being opened.
The second thing you need to know is that open won’t call the event handlers when it wants to fire the events. It will put the events into an ordered queue to be dealt with later. So the fact that it might not have anything assigned to deal with the events isn’t a problem.
The third thing you need to know is that when the browser finishes the code that ran when the pick button was pressed it then goes through the queue of events that have been raised and calls each one in turn. This happens when the event handlers have been assigned, so they all run and do what we want.
This makes perfect sense. In the code above the user presses the “Choose a folder” button. This calls the pick function which pops up the file picker, captures the folder and then pops it in the database. We don’t want our button handler to have to hang around waiting for the database to catch up. We want it to return to the user so that they can do other things. When the database does catch up, the events need to fire and sort everything out.
JavaScript is super clever. But it can also be super-confusing sometimes.