【问题标题】:indexeddb get data from index n to index kindexeddb 从索引 n 到索引 k 获取数据
【发布时间】:2021-01-20 08:52:26
【问题描述】:

如何从索引号 n 到 k 的对象存储中获取数据。 例如,如果我们在商店(ProductStore)中有 100 条记录,我需要从索引 11 到 20 或从 50 到 60 获取。我需要在分页中使用它。在 mysql 中我们可以使用 LIMIT 和 OFFSET clouse,在 Indexeddb 中是否有任何等效的 OFFSET。

【问题讨论】:

    标签: javascript indexeddb


    【解决方案1】:

    您可以使用cursor.advance 跳过一些记录。游标没有限制,您只需通过计算迭代次数来停止迭代。

    类似这样的:

    function query(db, criteria, offset, limit) {
      return new Promise((resolve, reject) => {
        const results = [];
        const transaction = db.transaction('store');
        transaction.oncomplete = event => resolve(results);
        transaction.onerror = event => reject(event.target);
        const store = transaction.objectStore('store');
        const index = store.index('index');
        const request = index.openCursor(criteria);
    
        let advanced = offset === 0;
        let counter = 0;
        
        request.onsuccess = event => {
          const cursor = event.target.result;
          if (!cursor) {
            return;
          }
    
          if (!advanced) {
            advanced = true;
            cursor.advance(offset);
          }
    
          counter++;
          results.push(cursor.value);
    
          if (counter >= limit) {
            return;
          }
          cursor.continue();
        };
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-17
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      相关资源
      最近更新 更多