无法从一堆嵌套函数中获得结果

时间:2014-10-17 10:56:05

标签: javascript

此示意图代码使用Google API request.execute方法以及匿名和递归函数的混合,此代码无法设置结果为UNDEFINED的iGlobal变量。

var iGlobal;

main();

function main(){
   f(g);                    //g - function that used to get result from anonymous function
   console.log(iGlobal);    //iGlobal is UNDEFINED
}

function f(g){
    var r = function(request, result) {
        request.execute(function(resp) {
            var b = resp.b;
            if (b) {
                r(request, result);
            } else {
                g(result);
            }
        });
    };
}

function g(result){
    iGlobal = result;
}

此简化代码可正常运行:

var iGlobal;

main();

function main(){
   f(g);                    //g - function that used to get result from anonymous function
   console.log(iGlobal);    //iGlobal is [object Object],[object Object]
}

function f(g){

    var b = true;

    (function () {
        var r = function() {
            if (b) {
                b = false;

                r();
            } else {
                var a = [];
                a[a.length] = {"1":1,"2":2};
                a[a.length] = {"1":1,"2":2};
                result = a;
            }
        };
    })();

    g(result);  
}

function g(result){
    iGlobal = result;
}

0 个答案:

没有答案