Working with IndexedDB, I have this code:
async function Get() {
const dataset=await db.result.transaction('Store1','readwrite').objectStore('Store1').get(5);
console.log(dataset);
}
I am expecting an object to be returned from this IndexedDB store:
This is what is returned:
How can I use await to get a text object from an IndexedDB store?
The IndexedDB
API simply isn't Promise-based (or, more generally, "Thenable"), so you can't treat it like a Promise.
What you can do, if you need a Promise-based interface, is wrap it in a Promise manually and return that from your function. For example:
async function Get() {
const store = db.result.transaction('Store1','readwrite').objectStore('Store1');
const dataset = await getFromObjectStore(store, 5);
console.log(dataset);
}
function getFromObjectStore(store, key) {
return new Promise((resolve, reject) => {
const request = store.get(key);
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
reject(request.error);
};
});
}
In this case getFromObjectStore
is simply a helper function which abstracts the onsuccess
and onerror
callbacks in a Promise.