IndexedDB – Promise Wrapper
Promises, like callbacks, are a technique of telling what you want your code to perform once an asynchronous operation completes without stopping the runtime’s thread of javascript.
Instead of supplying a callback to an asynchronous function to run after it completes, promises can be used instead.
Promise library was created by Jake Archibald and it uses promises rather than events.
It is easier to use than the traditional IndexedDB. It simplifies the API while still maintaining its structure.
Here we are showing the enhancements only as to why we can use the Promised library to know more about it you can visit the following website −
It has a few enhancements −
- IDBDatabase
- IDBTransaction
- IDBCursor
IDBDatabase
Shortcuts to get or set from an object store
const value = await db.get(storeName, key); await db.put(storeName, value, key);
Shortcuts to get from an Index
const value = await db.getFromIndex(storeName, indexName, key);
IDBTransaction
tx.store
If a transaction is a single store the store property references the store or else it is undefined then we use
const tx = db.transaction(''any transaction''); const store = tx.store; tx.objectStore(storeName);
tx.done
The .done promise resolves when a transaction is completed successfully else it rejects with a transaction error.
const tx = db.transaction(storeName, ''readwrite''); await Promise.all([ tx.store.add(''one'', ''two''), tx.store.put(''three'', ''four''), tx.done, ]);
IDBCursor
The cursor advance methods are −
- Advance
- Continue
- ContinuePrimaryKey
They return a promise to cursor or else it returns null.
let cursor = await db.transaction(storeName).store.openCursor(); while (cursor) { document.write(cursor.key, cursor.value); cursor = await cursor.continue(); }