how to make synchronous call to indexeddb method from javascript

删除回忆录丶 提交于 2019-12-01 22:33:02

问题


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


回答1:


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
    }); 
}


来源:https://stackoverflow.com/questions/13972243/how-to-make-synchronous-call-to-indexeddb-method-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!