Ravi
Ravi

Reputation: 181

how to make synchronous call to indexeddb method from javascript

I have one method say method1 in java script that is having another method say method2 call. method2 returns one value which is needed in method1 after method2() call.

var userObj={"first": [{'Key':'1',
               'value':'student',},
                          {'Key':'2',
               'value':'Teacher',}
                 ],
        "second":[{'Key':'1',
               'class':'theory',},
                          {'Key':'2',
               'value':'lab',}
                 ]

            };

function method1(){
    var dataArray =method2(userObj.first);  
    alert("dataArray size -"+dataArray.length);
}

function method2(firstData) {

        var dataArray = new Array();
        $.indexedDB("SelfAssessment").objectStore("First_Sheet", "readonly").each(function(elem) {
            dataArray .push(elem.value);
        }).done(function() {
            alert("inside first Data");
            return dataArray ;
        });
        return dataArray ;

    }

In the above code method2 returns dataArray that i have to use in method1. so how to do this ?

Since, method2 is asynchronous call so, i am getting "first alert" before "alert inside method2". How to get this in a sequential way ?

plz help

Upvotes: 3

Views: 2009

Answers (1)

apsillers
apsillers

Reputation: 116030

Don't have method2 return a value. Instead, pass a callback function to method2 which will execute once the value has been fetched:

function method2(firstData, completionCallback) {

    var dataArray = new Array();
    $.indexedDB("SelfAssessment").objectStore("First_Sheet", "readonly").each(function(elem) {
        dataArray.push(elem.value);
    }).done(function() { completionCallback(dataArray) });
}

And invoke it like this:

function method1(){
    method2(userObj.first, function(dataArray) {
        // inside a function that is called by method2 when the value is fetched
        alert("dataArray size -"+dataArray.length);

        // do everything with dataArray inside this function
    }); 
}

Upvotes: 4

Related Questions