如何在IndexedDB中获取onsuccess事件的返回值?

ki0zmccv  于 2023-04-27  发布在  IndexedDB
关注(0)|答案(1)|浏览(287)

我使用IndexedDB在客户端存储数据,以便在应用中切换标签时保存数据,使用.get()方法时无法获取onsuccess事件的返回值,请指教。
下面是代码
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

如何将onsuccess事件的返回值导入数据变量?
谢啦

eoigrqb6

eoigrqb61#

问题是getFromIndexedDbSession是异步的,get操作通过事件处理程序`返回一个值。
您可以尝试返回结果以等待它:

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');
    };
  });
}

然后,你可以使用Promise来获取student的值:

getFromIndexedDbSession("example")
  .then((student) => {
    console.log(student);
  })
  .catch((error) => {
    console.error(error);
  });

相关问题