1 例子
export async function funcGetKey(dbName, tableName) {return new Promise((resolve, reject) => {// 打开指定的数据库const request = indexedDB.open(dbName);request.onerror = (event) => {console.error('打开数据库失败: ', event.target.error);reject(event.target.error);};request.onsuccess = (event) => {const db = event.target.result;const transaction = db.transaction([tableName], 'readonly');const objectStore = transaction.objectStore(tableName);const keysRequest = objectStore.getAllKeys(); // 获取所有 key 值的请求keysRequest.onsuccess = (event) => {const keys = event.target.result; // 获取所有的 key 值console.log(keys);resolve(keys);};keysRequest.onerror = (event) => {console.error('获取 key 值出错', event.target.error);reject(event.target.error);};};});
}
2 IDBRequest对象取 result中的值
IDBRequest {source: IDBObjectStore, transaction: IDBTransaction, readyState: 'pending', onsuccess: null, onerror: null}
error: null
onerror: null
onsuccess: null
readyState: "done"
result: []
keysRequest.onsuccess = (event) => {const keys = event.target.result; // 获取所有的 key 值console.log(keys);resolve(keys);};
3 ps
keys
是一个 IDBRequest
对象,而不是直接包含 key 值的数组。所以你需要等到 IDBRequest
对象的 onsuccess
事件触发后,才能获取到 key 值的数组。在 onsuccess
事件处理函数中,你可以使用 event.target.result
属性来获取数据,即 keys = event.target.result
。然后你就可以通过 keys
数组来获取所有的 key 值了。