`title: IndexedDB 范围查询与分页游标最佳实践``categories: Web 开发/前端/数据管理``keywords: IndexedDB,范围查询,IDBKeyRange,游标,分页``description: 使用 IDBKeyRange 与游标实现时间窗与主键范围查询的高效分页,并给出去重与下一页定位策略。`示例async function pageByRange(db, idxName, lower, upper, limit = 50, afterKey) { return new Promise((resolve, reject) => { const tx = db.transaction('items', 'readonly'); const idx = tx.objectStore('items').index(idxName); const range = IDBKeyRange.bound(lower, upper); const out = []; let count = 0; idx.openCursor(range, 'next').onsuccess = e => { const c = e.target.result; if (!c) return resolve({ items: out, nextKey: undefined }); if (afterKey && c.key <= afterKey) { c.continue(afterKey); return; } out.push(c.value); if (++count >= limit) return resolve({ items: out, nextKey: c.key }); c.continue(); }; tx.onerror = () => reject(tx.error); }); }

发表评论 取消回复