访问indexedDB请求的结果(在数组中)

时间:2015-04-29 08:17:19

标签: indexeddb

我试图使用以下代码获取我的一个objectStore的迭代对象的值:

enter codefunction get_object(object){
    var object = object;
    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 + "...");
            return obj_list;
        }
    };
}

我想要做的是在所述方法之外访问obj_list?

2 个答案:

答案 0 :(得分:0)

将您的主要功能更改为以下内容:

function get_object(object){
    return new Promise(function(resolve, reject) {
        var object = object;
        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 + "...");
                resolve(obj_list);
            }
        };
    });
}

然后访问它:

get_object('some_object').then(function (returned_data) {
    console.log(returned_data);
});

答案 1 :(得分:0)

Jonny展示了正确的道路。如果你不是一个JS极客并且不想使用promises并且相信回调方法,那么一个简单的代码如下:

function get_object(object, callBack){
    var object = object;
    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
}