For example
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
// these event handlers act on the database being opened.
DBOpenRequest.onerror = (event) => {
note.innerHTML += "<li>Error loading database.</li>";
};
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
};
What I understand is that DBOpenRequest.onerror = xxx
is setting an event listener to handle the event error
.
But why we set the event handler after the event emitting statement (i.e. the open action const DBOpenRequest = window.indexedDB.open
) is executed, not before?
Isn’t it possible that after the the event emitting statement is executed and before we set the error
event handler, the event is already emitted, so that it is never captured by any event handler (since there is none at all)?
2
Answers
JavaScript has "run to completion" semantics; that is, the code you write won’t be interrupted by an event firing in the middle of the code block. The event handler won’t be invoked until after your code has finished running and returned control to the browser.
Accessing
IndexedDB
is an asynchronous task. The way JavaScript works is your program starts running, and when it runs into an asynchronous task, it says "Let’s go ahead and do all the synchronous tasks because those are generally faster, then we’ll go back and do the asynchronous tasks, in order, after that," and it adds the task to a queue to return to later.So
window.indexedDB.open()
gets added to the queue, then the program assigns your event listeners, then it executeswindow.indexedDB.open()
.Here’s a great video about how the JavaScript event loop works.