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.getStdOptionsis an asynchronous operation, yourgetStdOptsis 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 intogetStdOptsa callback which would takevalsas a parameter and execute that callback within your anonymous one forthis.srvs.getStdOptions, or you need to return some sort of promise object to which you can add callbacks (which would essentially take the samevalsas a parameter) as needed– you’d have to resolve in your anonymous callback your promise to havevalsas its “promised” results.