Question:
I am reading a book about the Html5 data storage IndexedDb. The IndexedDb API uses the following code to open a database connection:
var request = indexedDB.open('some name');
request.onsuccess = function(event) {
obj.id = event.target.result
}
request.onerror = function(event) {...}
The request variable is assigned a callback which is called when the request was executed successfully. But the request gets never called after those lines. So my question is:
How does the onsuccess callback get executed? It can't be in in the indexedDB.open method because there the onsuccess callback wasn't assigned yet?
What am I missing?
Edit:
After the comment from James I found the missing link to my question:
Say it with me now: async programming does not necessarily mean multi-threaded. Javascript is a single-threaded runtime - you simply aren't able to create new threads in JS because the language/runtime doesn't support it.
source: How does Asynchronous programming work in a single threaded programming model?
Solution:
As James points out in his answer below, async functions like indexedDB.open() are pushed into a special queue known as the “event loop”:
The event loop is a special queue for callback functions. When an async code is executed, a callback is then pushed into the queue. The Javascript engine will only execute the event loop if the code after the async function has finished executing.
source: http://www.hiddenwebgenius.com/blog/guides/understanding-javascripts-asynchronous-code/