如何从javascript IndexedDB的方法同步调用 [英] how to make synchronous call to indexeddb method from javascript

查看:557
本文介绍了如何从javascript IndexedDB的方法同步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,说的方法1 在这是有另一种方法说的方法2 调用Java脚本。 方法2 返回这是需要在方法1方法2()调用后一个值。

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 ;

    }

在上面的code方法2回报DataArray中,我有方法1使用。因此,如何做到这一点?

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

一直以来,方法2是异步调用的话,我在里面方法2警报之前得到第一个警报。如何在一个连续的方式得到这个?

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

plz帮助

推荐答案

不用方法2 返回一个值。相反,传递一个回调函数 方法2将执行一次数值已经被抓走:

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

和调用它是这样的:

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

这篇关于如何从javascript IndexedDB的方法同步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆