如何在IndexedDB的单个事务中获取多个ObjectStore
解决IndexedDB多ObjectStore批量获取数据的问题
你的代码核心问题在于:IDBTransaction.objectStore()方法只能传入单个ObjectStore名称,不能直接传数组,这会直接导致调用报错。要一次性获取多个仓库的数据,需要分别处理每个仓库的查询操作,再合并结果。
正确实现方式
可以用Promise封装每个仓库的getAll()请求,通过Promise.all()并行执行所有查询,最后统一汇总结果:
// 假设db是已打开的IndexedDB实例 const targetStores = ['category', 'time']; const transaction = db.transaction(targetStores, 'readonly'); // 为每个仓库创建获取数据的Promise const fetchTasks = targetStores.map(storeName => { return new Promise((resolve, reject) => { const store = transaction.objectStore(storeName); const request = store.getAll(); request.addEventListener('success', () => { resolve({ [storeName]: request.result }); }); request.addEventListener('error', (e) => { reject(e.target.error); }); }); }); // 等待所有查询完成,合并结果 Promise.all(fetchTasks) .then(results => { // 合并成键为仓库名、值为对应数据的对象 const allStoreData = Object.assign({}, ...results); console.log('所有仓库数据:', allStoreData); }) .catch(err => { console.error('批量获取数据失败:', err); });
代码说明
- 先创建包含所有目标仓库的只读事务,确保所有查询在同一个事务上下文执行
- 遍历每个仓库,单独调用
objectStore()获取实例后发起getAll()请求 - 用Promise封装每个请求的成功/失败回调,便于并行处理
- 通过
Promise.all()等待所有请求完成,将结果合并为结构化对象,方便后续使用
内容的提问来源于stack exchange,提问作者Gu Ro
相关产品推荐
相关产品推荐

