使用IndexedDB游标进行分页

Ben*_*lts 6 javascript html5

我有一个IndexedDB数据存储,其中包含几百个对象.我想根据该商店的一个索引中的订单从中获取40-59项.有没有办法在开始使用数据之前简单地调用cursor.continue()39次?就处理时间而言,这似乎相当浪费.

Pet*_*ham 6

我有同样的问题,cursor.advance(40)是你想要使用的.

我花了一段时间才弄明白的一件事可能对其他人有用,如果你想要推进光标并遍历结果,你需要在不同的openCursor().onsuccess处理程序中调用它们,或者实现某种跟踪以防止它们在同一个请求中被调用或被InvalidStateError抛出的异常.这可以这样做:

单独的处理程序

// advance first
store.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    cursor.advance(40);
};

// then iterate
objectStore.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    cursor.continue();
});
Run Code Online (Sandbox Code Playgroud)

相同的处理程序

// create flag for advancing
var advancing = true;

store.openCursor().onsuccess = function(event) {

    var cursor = event.target.result;

    // advancing
    if (advancing === true) {

        cursor.advance(40);

        // set advancing flag to false so we don't advance again
        advancing = false;

    }
    // continuing
    else {

        cursor.continue();

    }

}
Run Code Online (Sandbox Code Playgroud)

规范参考:http://www.w3.org/TR/IndexedDB/#widl-IDBCursor-advance-void-unsigned-long-count MDN参考示例:https://developer.mozilla.org/en-US/文档/网络/ API/IDBCursor.advance


Joh*_*ert 2

我相信你可以打电话cursor.advance(40)

规范参考:http://www.w3.org/TR/IndexedDB/#widl-IDBCursor-advance