简体   繁体   中英

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.

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. When accessed from within the inner function, vals contains all the elements as expected.

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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