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

IndexedDB记录添加成功但inUse索引无数据,求排查原因

IndexedDB inUse索引无数据问题排查

问题描述

我正在使用IndexedDB和idb promise库,创建了名为storeMappings的对象仓库,并创建了inUse索引。随后向该仓库填充了若干记录,所有操作看似正常,但inUse索引未显示任何数据,请问可能的原因是什么?

原代码

const _addStoreMappings = async (db) => {
  const mappings = db.createObjectStore('storeMappings', {                            
    keyPath: 'id', 
    autoIncrement: true,                                                              
  });                                                                                 
  
  await mappings.createIndex('inUse', 'inUse');                                       
  
  await mappings.add({ store: `store0`, name: `foo store`, inUse: true });            
  
  Array.fromAsync({ length: 14 }, (_, i) => (
    mappings.add({ store: `store${++i}`, name: '', inUse: false })                    
  ));                                                                                 
};  

问题截图

仓库记录截图
索引无数据截图

原因分析及解决方案

核心问题

  1. 错误使用await调用createIndex:IndexedDB的createIndex是同步操作,并非异步方法,用await会打乱事务的执行时序,导致索引可能未完全创建就开始写入数据,最终索引无法关联记录。
  2. 批量添加未等待异步完成:Array.fromAsync生成的Promise数组没有被等待,这些add操作可能在事务结束后才执行,数据未正确写入仓库,自然索引也没有对应的条目。

修正后的代码

const _addStoreMappings = async (db) => {
  const mappings = db.createObjectStore('storeMappings', {                            
    keyPath: 'id', 
    autoIncrement: true,                                                              
  });                                                                                 
  
  // createIndex是同步操作,无需await
  mappings.createIndex('inUse', 'inUse');                                       
  
  await mappings.add({ store: `store0`, name: `foo store`, inUse: true });            
  
  // 用Promise.all等待所有添加操作完成,确保事务内执行完毕
  await Promise.all(Array.from({ length: 14 }, (_, i) => (
    mappings.add({ store: `store${i + 1}`, name: '', inUse: false })                    
  )));                                                                                 
};  

修正说明

  • 移除await调用createIndex:同步方法直接执行即可,保证索引在数据写入前创建完成。
  • 替换Array.fromAsync为Array.from:此处无需异步迭代,普通数组生成足够;同时用Promise.all包裹所有add操作,确保所有数据写入都在当前事务内完成,避免事务提前结束导致数据丢失。

内容的提问来源于stack exchange,提问作者dman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:03:19