I came across the need to return a value from one function to another and for a while scratched my head in confusion when this simple task didn’t work. I then realised I was operating within a closure function (or anonymous function?) and can’t find documentation on how to release a variable out of such a function’s scope.
For example, this doesn’t work:
function aFunc()
{
var result;
object.event = function(){
result = true;
}
return result;
}
Nor does returning from inside the closure. Do I need to do both? I tried using a global variable within the largest scope possible (outside of all functions) and this didn’t work either. What am I missing?
I’m not sure whether I’m using the term closure correctly, I’m referring to the anonymous function.
Thanks.
You need to call the closure:
Or, if it runs elsewhere, this is a timing issue. You can have something like a promise:
But, a simple callback should suffice. Since you mentioned the
XMLHttpRequestobject, you should be able to attach a callback to itsonreadystatechangeevent, or pass a callback toaFunc:Then your callback gets called with the result at the time it is available.