嵌套函数未返回

Nested functions not returning

本文关键字:返回 函数 嵌套      更新时间:2023-09-26

我正在构建一个phonegap应用程序。我使用的是一个web sql,在数据检索之前一切都很好。

function getItemGroups(){
    var items_groups = new Array();
    var db = window.openDatabase("merbokDB", "1.0", "MerbokDB", 5232394);
    db.transaction(
        function(tx){
            tx.executeSql('SELECT * FROM item_groups',[],
                function(tx,result){
                    if(result.rows.length > 0){
                        var len = result.rows.length;
                        for (var i=0; i<len; i++){
                            items_groups.push(result.rows.item(i).item_group);
                        }
                        console.log(items_groups.join());
                    }
                }
                ,errorCB);
        },
        errorCB);
    return items_groups;
}
var myproducts = getItemGroups();

我的问题是,当我运行代码时,"myproducts"变量为空。但是我能看到

console.log(items_groups.join());

下面一行在控制台中打印值。我回来的方式错了吗?

我对您使用的框架不是100%熟悉,但一个很好的猜测是,传递到链中每个步骤的函数都是用于异步回调的。因此,不能保证它们会在运行语句之前运行。所以本质上发生的是这条线:

return items_groups;

在执行这些内部函数中的任何一个之前执行。所以它只是返回它的初始值,这是一个空数组。

片刻后(甚至几毫秒后),内部函数被执行,控制台日志输出被看到。

当使用这样的异步功能时,不能依赖于按顺序执行的代码行序列。与其在"下一行"执行逻辑,不如在某种回调函数中执行。在这种情况下,检索数据后的最终回调似乎是这样的:

function(tx,result){
    if(result.rows.length > 0){
        var len = result.rows.length;
        for (var i=0; i<len; i++){
            items_groups.push(result.rows.item(i).item_group);
        }
        console.log(items_groups.join());
    }
}

无论要对myproducts变量执行什么操作,都需要在该函数中启动。