Reputation: 19717
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?
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?
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/
Upvotes: 0
Views: 301
Reputation: 14783
If indexedDB.open executes the request asynchronously then the request won't be completed until after your code relinquishes control, so request.onsuccess will have been assigned by then.
Javascript in the browser is single threaded so there is no chance of the request completing before onsuccess / onerror is assigned
Upvotes: 2