Question

I'm making some prototype app who is using indexdDB and I can't figure out how to create reusable function. For example I would like to create reusable function to retrieve LOV values. I know that it should be create somehow via events but I can't figure out how. Could anyone please help?

Below is the code what I would like to bring in life

function parent(){
    var lovValues = getLovValuesByType("STORE_TYPE");
    //lovType now is undefined
};

function getLovValuesByType(lovType){
    var returnedLovValues = new Array();
    var t = db.transaction(["LST_OF_VAL"], "readonly");
    var objectStore = t.objectStore("LST_OF_VAL");
    var INDEX = objectStore.index("TYPE");
    var REQUEST = INDEX.openCursor(IDBKeyRange.only(lovType));
    REQUEST.onsuccess = function() {
        var CURSOR = REQUEST.result;
        if (CURSOR) {
            var value = this.result.value.VAL;
            returnedLovValues.push(value);
            this.result.continue();
        } else {
            return returnedLovValues; /// <------return data
        };
    };
};
Was it helpful?

Solution

Your return statement is returning from the callback function REQUEST.onsuccess. You don't return anything from getLovValuesByType, which is why lovValues is undefined.

The most straightforward solution is to use a callback function:

getLovValuesByType("STORE_TYPE", function (lovValues) {
    //lovType now is defined
);

function getLovValuesByType(lovTypem, cb){
    var returnedLovValues = new Array();
    var t = db.transaction(["LST_OF_VAL"], "readonly");
    var objectStore = t.objectStore("LST_OF_VAL");
    var INDEX = objectStore.index("TYPE");
    var REQUEST = INDEX.openCursor(IDBKeyRange.only(lovType));
    REQUEST.onsuccess = function() {
        var CURSOR = REQUEST.result;
        if (CURSOR) {
            var value = this.result.value.VAL;
            returnedLovValues.push(value);
            this.result.continue();
        } else {
            cb(returnedLovValues);
        };
    };
};

More generally, you might want to do some reading about asynchronous JavaScript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top