Contact Us

 Vikas     Feb,08 2017

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)

var db;var request ="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 =; //both are validconsole.log(db); //get the object};console.log(db); //get undefined

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

alert("Database is: " + db);

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.

var timer = setInterval(function() {if(!db) // Not ready yet.return;// We have a db so we can stop waitingclearInterval(timer);// and get on with our real work.start_main_application();}, 100);function start_main_application(){console.log(db);//do rest of the 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?