离线缓存里一次性读几百条记录,游标遍历的回调能拖出卡顿——getAllRecords() 把这件事收成了一次调用
每次做离线缓存都要写一整套 IndexedDB 的游标遍历,一次读几百条记录,光 cursor.continue() 的异步回调就能把主线程拖出卡顿——这不是你代码写得烂,是 IndexedDB 的读 API 三十年没变过。
Chrome 141 给 IDBObjectStore 和 IDBIndex 加了一个 getAllRecords(),外加给 getAll()/getAllKeys() 补了个 direction 参数。一句话:以前要开游标一条条读的批量读取,现在能一次拿回「主键 + 值 + 索引键」的完整集合,少掉一整层回调。
以前怎么读一批记录
假设做一个离线消息队列,按时间戳索引取出某个会话的最近 500 条:
// Before:游标遍历,一条一条读
function getAllByCursor(db, roomId) {
return new Promise((resolve, reject) => {
const tx = db.transaction('messages', 'readonly');
const index = tx.objectStore('messages').index('by_room');
const range = IDBKeyRange.only(roomId);
const out = [];
const req = index.openCursor(range);
req.onsuccess = (e) => {
const cursor = e.target.result;
if (!cursor) return resolve(out);
out.push({ key: cursor.primaryKey, value: cursor.value, indexKey: cursor.key });
cursor.continue(); // 每次 continue 都是一次异步往返
};
req.onerror = () => reject(req.error);
});
}
这种写法的问题在于:每条记录触发一次事件循环往返,500 条 = 500 次回调。在低端安卓机上,这段逻辑放在主线程里跑几千条,肉眼可见掉帧。所以过去大家要么挪到 Web Worker,要么分页,要么干脆换 localStorage。
现在怎么读
// After:一次调用拿全量
async function getAllByRecords(db, roomId) {
const tx = db.transaction('messages', 'readonly');
const index = tx.objectStore('messages').index('by_room');
const records = await index.getAllRecords(IDBKeyRange.only(roomId));
// records: [{ key, value }, ...] —— IDBIndex 还额外带 indexKey
return records;
}
getAllRecords() 本质上是把 getAllKeys() 和 getAll() 合并成一次操作,同时枚举主键和值。用在 IDBIndex 上时,返回的每条还多一个 indexKey 字段。返回值是个 Promise(不是老的 request 对象),可以直接 await。
direction 参数补在 getAll() 和 getAllKeys() 上,取值 ‘next’ / ‘nextunique’ / ‘prev’ / ‘prevunique’——意思是倒序取「最近 N 条」时不用再自己 reverse 数组了:
// 倒序取最近 50 条,直接一步到位
const latest = await store.getAll(IDBKeyRange.upperBound(Date.now()), 50, 'prev');
实测数字
Chrome 官方在发布说明里给了一组对比:在一个「微软属性」的基准 workload 上,用 getAllRecords() 替代游标遍历,读完一批记录快了约 350ms。这个数字单看不大,但离线优先的 App 里这种读取往往在启动路径上,350ms 直接决定首屏是先出骨架还是一闪而过。
换到 API 形态上,before/after 的差别更直白:
- Before:
openCursor+onsuccess里循环cursor.continue(),N 条记录 ≈ N 次异步往返 - After:
getAllRecords(range)一次调用,返回 Promise,N 条记录一次批量读
三个要留意的点
- 单次读的量有个上限,超大结果集会一次性进内存,比游标更容易触发内存峰值,别一次性把整表读进来。
- getAllRecords 只在 IDBObjectStore 和 IDBIndex 上,IDBCursor 没有这个快捷方法,混合旧代码时要分清。
- 兼容性:Chrome 141(2025-09 发布)开始支持,其他核心引擎跟进中。想稳妥上线,先写
if ('getAllRecords' in store)的特征检测,降级回游标版本。
下一步
翻一遍你项目里所有 openCursor 的调用点,把「只读、无过滤逻辑」的那几处批量读,换成 getAllRecords() + direction,优先动启动路径和 Web Worker 里的读取——这两处对延迟最敏感。改完用 Performance 面板对比一下长任务数量,通常能看到明显下降。
评论区
登录后可评论。