I cannot for the life of me figure out why async/await behaves the way it does.
Consider this example.
I want a function that does some db initialization, and returns me the database object when it is done.
var globalDb = null;
const IDB_DATABASE_NAME = "mydb";
const IDB_STORE_NAME = "mystore";
const IDB_VERSION = 1.0;
async function initDb() {
var idbOpenDbRequest = window.indexedDB.open(IDB_DATABASE_NAME, IDB_VERSION);
idbOpenDbRequest.onsuccess = function (event) {
return event.target.result;
};
}
(async () => {
globalDb = await initDb();
console.log("I should happen second")
console.log(globalDb);
})();
Expected
- console.log("I should happen first")
- console.log("I should happen second")
- console.log(globalDb); //dumps the object to console
Actual
- console.log("I should happen second")
- console.log(globalDb); //undefined
- console.log("I should happen first")
I realize I am fundamentally misunderstanding something here. Please enlighten me why await does not work as I would expect. :)
JsFiddle
https://jsfiddle.net/p2jqyrou/2/
Ps. Forget that this is about indexedDb and that this example is extremely simplified - I don't think it matters for the topic of this question.