You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从IndexedDB的onsuccess事件中获取.get()方法的返回值?

解决IndexedDB异步获取数据无法返回值的问题

你的问题核心在于IndexedDB的所有操作都是异步事件驱动的,而你的函数是同步执行的——函数会在异步操作完成前就返回,所以data拿到的是undefined,onsuccess里的return也只是该回调函数的返回值,不会传递到外层函数。

要解决这个问题,你需要用Promise来包裹异步操作,把异步结果通过Promise的resolve返回,之后通过async/await或者.then()来获取结果。

修改后的代码:

function getFromIndexedDbSession(key) {
    return new Promise((resolve, reject) => {
        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变量,避免全局污染
            const getRequest = db.transaction('tool').objectStore('tool').get(key);
        
            getRequest.onsuccess = (e) => {
                const student = e.target.result;
                console.log(student);
                resolve(student); // 用Promise返回结果
            };
        
            getRequest.onerror = (err) => {
                console.error(`获取数据失败: ${err}`);
                reject(err); // 传递错误信息
            };
        };
        
        openRequest.onerror = function (e) {
            console.log('数据库打开失败');
            reject(e.target.error);
        };
    });
}

// 调用方式1:使用async/await(需在async函数内执行)
async function fetchData() {
    try {
        const data = await getFromIndexedDbSession("lan");
        console.log('获取到的数据:', data);
        // 在这里处理data
    } catch (err) {
        console.error('请求出错:', err);
    }
}
fetchData();

// 调用方式2:使用.then()链式调用
getFromIndexedDbSession("lan")
    .then(data => {
        console.log('获取到的数据:', data);
        // 处理data
    })
    .catch(err => {
        console.error('请求出错:', err);
    });

关键修改点:

  1. 用new Promise()包裹整个IndexedDB操作流程,通过resolve()返回成功结果,reject()传递错误。
  2. 外层函数直接返回这个Promise对象,让调用方可以通过异步方式获取结果。
  3. 修复了getRequest未声明变量的问题,避免全局变量污染。
  4. 提供两种调用方式:async/await(更直观的同步写法)和.then()(传统异步链式写法)。

内容的提问来源于stack exchange,提问作者Surendranatha Reddy T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:55:00