8

While reading the HTML5 IndexedDB Specification I had some doubts about its asynchronous request model. When looking at the request api example, the open method is used to start an async request.

var request = indexedDB.open('AddressBook', 'Address Book');
request.onsuccess = function(evt) {...};
request.onerror = function(evt) {...};

At the time this request is started, there are no event handlers defined yet.

  • Isn't this a race condition?
  • What happens when the open method succeeds before the javascript interpreter executes the assignment to onsuccess?
  • Or is the request only really started once both callbacks are registered?

In my opinion an api like the following would be much more logical:

db.open('AddressBook', 'Address Book', {
    onsuccess: function(e) { ... },
    onerror  : function(e) { ... }
});

1 Answer 1

6

There will be no race condition because JavaScript engine will finish executing actual scope (function) and then fire any callback or event handler. Read following comment on Mozilla Hacks.

Sign up to request clarification or add additional context in comments.

2 Comments

Good find, the keywords to search for seem to be "run to completion". That explains why the code works without any races, but I still think its a sign of bad api design.
Are there ways to defer it, so one can open the request in the developer console and then execute it after defining the callbacks? Or define the callbacks and then open the request?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.