Casebash
Casebash

Reputation: 118742

Creating an indexedDB and creating an object store

I've been looking at tutorial for how to work with indexedDB. It suggests the following code.

dbreq = window.indexedDB.open('testaaaaa');
dbreq.onupgradeneeded = function(event){
    var db = event.target.result;
    var objectStore = db.createObjectStore("cats");
    console.log("hi");
}

VM321:5 hi

It works if I paste them into the Javascript console together.But then if I try typing them separately:

dbreq = window.indexedDB.open('testbbbbb');

Then:

dbreq.onupgradeneeded = function(event){
    var db = event.target.result;
    var objectStore = db.createObjectStore("cats");
    console.log("hi");
}

There is no output.

So this way of setting up a database technically creates a race condition, although this is unlikely to ever be hit. Is there a better way to create an object store that doesn't do this?

Upvotes: 0

Views: 330

Answers (1)

Joshua Bell
Joshua Bell

Reputation: 8337

JavaScript has what are called "run to completion" semantics. That means that execution will not be interrupted in the middle of executing a block of code to run some other code in the same context. So this is fine, since it's happening in one block:

// make the request
var request = indexedDB.open( ... );

// hook up the event listener
request.onupgradeneeded = function(e) { ... };

// hook up another event listener
request.onsuccess = function(e) { ... };

The events will not fire until the end of the whole block of JS is reached, so there's no race. Behind the scenes there may be an "upgradeneeded" event queued up waiting to be dispatched, but until that whole block of JS code completes it won't.

When you type the lines separately then you're splitting it up into multiple blocks and you're right: there's a race between the event coming back and how fast you type the second line of code. (And you probably don't type fast enough to win the race!)

Upvotes: 1

Related Questions