IndexedDB 提供了一个客户端存储大量结构化数据的能力,使得 Web 应用程序即使在网络不可用的情况下也能访问数据,这对于构建离线优先或者对网络依赖较小的应用至关重要。
IndexedDB提供了指针对象 IDBCursor,监听onsuccess事件以遍历数据。
阮一峰的网络日志给出了遍历的示例,如下:
function readAll() {var objectStore = db.transaction('person').objectStore('person');objectStore.openCursor().onsuccess = function (event) {var cursor = event.target.result;if (cursor) {console.log('Id: ' + cursor.key);console.log('Name: ' + cursor.value.name);console.log('Age: ' + cursor.value.age);console.log('Email: ' + cursor.value.email);cursor.continue();} else {console.log('没有更多数据了!');}};
}readAll();
其他资料提到的方法基本相似。
按照以上方式,如果需要对indexedDB操作进行封装,对开发者就不太友好了,咨询了国产大模型,给出用Promise实现的异步遍历,对于下一步的封装比较方便。
function openDB(name, version) {return new Promise((resolve, reject) => {let request = indexedDB.open(name, version);request.onsuccess = () => resolve(request.result);request.onerror = () => reject(request.error);});
}function iterateWithPromise(dbName, storeName) {return new Promise(async (resolve, reject) => {try {const db = await openDB(dbName, 1);const transaction = db.transaction([storeName], "readonly");const objectStore = transaction.objectStore(storeName);const allEntries = [];objectStore.openCursor().onsuccess = function(event) {const cursor = event.target.result;if (cursor) {allEntries.push(cursor.value);cursor.continue();} else {resolve(allEntries); // 遍历完成,返回所有条目}};transaction.onerror = reject;} catch (error) {reject(error);}});
}// 使用示例
iterateWithPromise("myDatabase", "myObjectStore").then(entries => console.log("所有条目:", entries)).catch(error => console.error("遍历出错:", error));