The IndexedDB API is mostly asynchronous. The API doesn't give you data by returning values; instead, you have to pass a callback function.
examples/web-worker/main.js
constcb= () => { // This is a callback fucntion }
You don't "store" a value into the database, or "retrieve" a value out of the database through synchronous means.
Instead, you "request" that a database operation happens.
examples/web-worker/main.js
let indexedDB =newIndexedDB();constcb= () => {indexedDB.get() };indexedDB.init(cb);}
You get notified by a DOM event when the operation finishes, and the type of event you get lets you know if the operation succeeded or failed. This sounds a little complicated at first, but there are sanity measures baked in. It's not that different from the way that XMLHttpRequest works.
Behind the Scenes
Let's take a look at indexed-db.js. We have very simple IndexedDB object.
examples/web-worker/assets/js/indexed-db.js
functionIndexedDB() {constname='ifc-js';constversion=1;consttransactionName='scene';var database;return {// Todo }}
As we discussed earlier, we "request" that a database operation happens. The initialization looks like this. Don't focus too much on the code. Simply note that we have a request, and it can either be
onupgradeneeded
onsucess
onerror
examples/web-worker/assets/js/indexed-db.js
init:function (cb) {var request =indexedDB.open(name, version);request.onupgradeneeded=function (event) {// DO STUFF };request.onsuccess=function (event) {// DO STUFF };request.onerror=function (event) {// DO STUFF }; },
Our code looks like this if we have successfully initilized the IndexedDB. Notice how the callback function, cb(), is used.
We start with indexedDB.init(cb) at row 11. Then, if the databased was initlized, we call indexedDB.get(...). The second parameter is another callback function. I.e. this part:
examples/web-worker/main.js
function (ifcFile) {// Do stuff});
At this point, the database might or might not exist. We need to check that.
examples/web-worker/main.js
function (ifcFile) {simpleCheck(ifcFile) ?parseIfcFile(input, myIfcFile) :rebuildScene(ifcFile.structured);});
Before we post our structure, we save it - see line 5. Let's open save-structured.js. This snippet works like the last one. Notice how we use the callback function.