简体   繁体   English

Javascript:外部函数中的变量不会被内部函数更改

[英]Javascript: variable in outer function not changed by inner function

I am having a small issue with what I believe is probably my misunderstanding of Javascript closures. 我对我相信Java闭包的误解有一个小问题。

I have this piece of code -- 我有这段代码-

getStdOpts: function(tbl, filt) {
    var vals = new Array();

    this.srvs.getStdOptions(
        { tbl: tbl },
        {
            'ok': function(rsp) {
                for (var i in rsp) {
                    vals.push({ value: rsp[i].id, text: rsp[i].descr });
                }
            }
        }
    );
    return vals;
}

In essence, although the inner function inside the getStdOptions call ('ok': function...) pushes new values into the vals array, when accessed from outside the call, the vals array is empty. 本质上,尽管getStdOptions调用中的内部函数(“ ok”:function ...)将新值推入vals数组,但从调用外部进行访问时,vals数组为空。 When accessed from within the inner function, vals contains all the elements as expected. 当从内部函数中访问时,vals包含所有预期的元素。

Would really appreciate any help I can get on this matter. 我真的很感激我能在这个问题上获得任何帮助。

I doubt this is a closure/scope issue. 我怀疑这是一个关闭/范围的问题。 If this.srvs.getStdOptions is an asynchronous operation, your getStdOpts is always going to return an empty array. 如果this.srvs.getStdOptions是异步操作,则您的getStdOpts总是将返回一个空数组。 This array would be filled once the operation completes, which, as written, would be after you would need it. 一旦操作完成,该数组将被填充,正如您所写的那样,将在您需要它之后。 You're going to have to handle things a bit differently. 您将不得不处理一些不同的事情。 Either you need to directly pass into getStdOpts a callback which would take vals as a parameter and execute that callback within your anonymous one for this.srvs.getStdOptions , or you need to return some sort of promise object to which you can add callbacks (which would essentially take the same vals as a parameter) as needed-- you'd have to resolve in your anonymous callback your promise to have vals as its "promised" results. 要么你需要直接传递到getStdOpts回调这将需要vals作为参数和您的匿名一个内执行的回调this.srvs.getStdOptions ,或者你需要返回某种承诺对象可向其中添加回调(这实际上将根据需要使用与参数相同的vals )-您必须在匿名回调中解析您希望将vals作为其“承诺”结果的承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM