0

I am using IndexedDB to store data on client side to preserve data when we switch tabs in application. I am unable to get return value of onsuccess event when I am working with .get() method, please advice.

Here is the code

sample.js

function getFromIndexedDbSession(key)
{
    let db;
    
    const openRequest = indexedDB.open('tool', 1);
    
    openRequest.onupgradeneeded = function (e) {
        db = e.target.result;
        const storeOS = db.createObjectStore('tool');
    
    };
    openRequest.onsuccess = function (e) {
        db = e.target.result;

        getRequest = db.transaction('tool').objectStore('tool').get(key);
    
        getRequest.onsuccess = (e)=> {
                const student = e.target.result;
                console.log(student)
                return student; //**This is not working, How can I return student value??**
            }
    
        getRequest.onerror = (err)=> {
            console.error(`Error to get student information: ${err}`)
        }
    
    };
    openRequest.onerror = function (e) {
        console.log('onerror! doesnt work');
    };
}


data = getFromIndexedDbSession("lan"); //here result of data is **undefined**, i want return value here

How can i get return value of onsuccess event into data variable?

Thanks,

  • 1
    [You can't](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). – Teemu Apr 19 '23 at 05:51

1 Answers1

1

The problem is that getFromIndexedDbSession is asynchronous, and the get operation returns a value through an event handler`.

You can try to return the result in order to wait for it:

function getFromIndexedDbSession(key) {
  return new Promise((RESOLVE, REJECT) => {
    const openRequest = indexedDB.open('tool', 1);

    openRequest.onupgradeneeded = function (e) {
      const db = e.target.result;
      const storeOS = db.createObjectStore('tool');
    };

    openRequest.onsuccess = function (e) {
      const db = e.target.result;

      const getRequest = db.transaction('tool').objectStore('tool').get(key);

      getRequest.onsuccess = (e) => {
        const student = e.target.result;
        RESOLVE(student);
      };

      getRequest.onerror = (err) => {
        REJECT(`Error to get student information: ${err}`);
      };
    };

    openRequest.onerror = function (e) {
      REJECT('onerror! doesnt work');
    };
  });
}

And, you can use the Promise to get the value of student:

getFromIndexedDbSession("example")
  .then((student) => {
    console.log(student);
  })
  .catch((error) => {
    console.error(error);
  });
Wandrille
  • 6,267
  • 3
  • 20
  • 43