Understanding Event Handler and Parallel Processing

These days I am trying to play with browser’s local database. I get very much interesting experience while assigning a value to variable.

I used the following code in JavaScript (Only works in Firefox)

[code:js]

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; //both are valid
console.log(db); //get the object
};

console.log(db); //get undefined
[/code]

In browser’s console, I get two outputs. One is undefined and another is Database Object.
I was wondering why it happens.

Moreover, first is says undefined. Then second is object. If I add one more line next to all code

[code:js]alert("Database is: " + db);[/code]

Then I get undefined, in result.

If I put alert() call in between then both results are same (database object).

After some time I realize that I was making an asynchronous call. Then I understood that onsuccess() was not just a handler or function but it is an “event handler” which will trigger when particular event occurs.

I should wait until this hander executed. Again as it is an asynchronous call, it will not notify us. We may need to use busy waiting function.

Thread that comes in mind! Lucky we have setInterval() function, to make some delay. Read more here.

[code:js]

var timer = setInterval(function() {
if(!db) // Not ready yet.
return;
// We have a db so we can stop waiting
clearInterval(timer);
// and get on with our real work.
start_main_application();
}, 100);

function start_main_application(){
console.log(db);
//do rest of the code.
}

[/code]

 

But then again, I can call start_main_application() function from handler itself!!!! no need to use timer!!

I really need to think difference between Synchronous and asynchronous, sequential and parallel execution, starting multi-threads and joining them.

After all, my question is can we convert synchronous call to asynchronous?