0

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:

IndexedDB database

This is what is returned:

Returned IDBRequest

How can I use await to get a text object from an IndexedDB store?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Some would call you a genius David. Good work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.