I’m trying following in Firefox 5.0:
var db;
var request = mozIndexedDB.open("MyTestDatabase");
request.onerror = function(event) {
alert("Why didn't you allow my web app to use IndexedDB?!");
};
request.onsuccess = function(event) {
db = request.result;
//db = event.target.result; //also tried this
console.log(db); //get the object
};
console.log(db); //undefined
I want db, accessible outside the handler. What is the issue here?
I am trying to learn something from this.
There must be a simple thing that I am missing..
Your
dbvariable is assigned a value inside the success handler:That handler will be called asynchronously and, in particular, it hasn’t been called when you do this:
so you end up with the initial value of
dbthat you get fromvar db;.So, you can access
dboutside the callback but it won’t necessarily have a useful value when you want it to. The usual approach is to put calls to things that needdbinside the success handler. If you need to usedbelsewhere, you’ll have to check that is is defined before you use it and wait if it isn’t.If you need to wait for
dbto be ready before continuing with your application then something like this should work:The
setIntervalwill trigger every 0.1s and check if there is adbyet; if it isn’t then it does nothing until the next time the interval is triggered; if there is adb, then it shuts down the timer and starts the main application.