indexedDB - objectStore.openCursor() 不会返回 objectStore 中的所有对象

标签 indexeddb cursors

我正在尝试使用 openCursor() 方法迭代“产品”objectStore 中的所有对象。

function getAllProducts(){
    var products = [];
    var transaction = db.transaction(["product"], "readonly");
    var objectStore = transaction.objectStore("product");

    objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
      if(cursor) {
        products.push(cursor.value);
        cursor.continue();
      } 
    };
}

我的“产品”objectStore 包含五 (5) 个对象。所以我预计我的产品数组的长度也为 5。然而,通过日志检查,迭代的对象数量似乎并不是恒定的。有时它只返回一 (1) 条记录,有时它只返回两 (2) 条记录。

我的代码有什么问题吗?我有什么遗漏的吗?

我尝试添加 onsuccess、onerror 和 onabort 句柄,但控制台中仍然没有其他日志。下面是我的更新代码:

function getAllProducts(){
    var products = [];
    var transaction = db.transaction(["product"], "readonly");
    var objectStore = transaction.objectStore("product");

    objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
      if(cursor) {
        products.push(cursor.value.name);
        cursor.continue();
      } 
      console.log(products);
    };

    transaction.oncomplete = function(event) {
        console.log(event);
    };

    transaction.onerror = function(event) {
        console.error(event);
    };

    transaction.onabort = function(event) { 
        console.log("YO YO YO");
        console.error("transaction aborted");
     }; 

}

最佳答案

这可能是因为您试图在光标完成循环/处理之前读取。我建议使用回调方法,该方法将在游标处理结束时调用最终结果集。 类似于(抛出代码来给你一个想法):

function get_object(object, callBack){
        var obj_list = [];
        var transaction = db.transaction([object],"readonly");
        var obj_store   = transaction.objectStore(object);

        obj_store.openCursor().onsuccess = function (event){
            cursor = event.target.result;
            if(cursor){
                console.log(cursor.value);
                obj_list.push(cursor.value);
                cursor.continue();
            }else{
                console.log("Done processing " + object + "...");
                if (callBack&& typeof(callBack) == 'function') {
                    callBack(obj_list);
                }
                return;
            }
        };
    }

然后将其用作:

get_object("data_store", callBack);
function get_object_result_processor(resultSet){
    //Do something
}

关于indexedDB - objectStore.openCursor() 不会返回 objectStore 中的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29914333/

相关文章:

MySQL 列标题为单列,第二列为值

oracle - PL/SQL 游标的变量/文字替换?

html - 在 IndexedDB 中保存 ArrayBuffer

sql-server - 解决游标问题

jasmine - 使用 Jasmine 进行浏览器的 IndexedDB 测试

ios8 - Indexeddb 不适用于来自网络应用程序的 iPhone IOS 8

postgresql - 将一条记录从游标发送到另一个函数Postgres

mysql - 在 MySQL 中使用游标时从 DECLARE 语句调用存储过程

javascript - Ember 异步计算属性返回未定义

javascript - IndexedDB 的包装函数