admin管理员组文章数量:1306063
I've built the function to return some variable. But my function uses another function asynchronously.
function getVariable() {
var myVariable;
asyncronousFunction(function(...){
myVariable = ...
});
return myVariable;
}
The problem is that myVariable
outside of and inside in asyncronousFunction
are different variables. So I can't assign value to myVariable
from asynchronous function.
How to resolve this scope problem? Thanks.
I've built the function to return some variable. But my function uses another function asynchronously.
function getVariable() {
var myVariable;
asyncronousFunction(function(...){
myVariable = ...
});
return myVariable;
}
The problem is that myVariable
outside of and inside in asyncronousFunction
are different variables. So I can't assign value to myVariable
from asynchronous function.
How to resolve this scope problem? Thanks.
Share Improve this question asked Aug 26, 2011 at 14:30 megasmegas 21.8k12 gold badges82 silver badges134 bronze badges2 Answers
Reset to default 5They are the same variable, but you cannot return
the result of an asynchronous function call synchronously from your getVariable
function. The value of myVariable
will be updated asynchronously at some unspecified later point in time. But your function is returning the value now. That doesn't work.
That means your getVariable
function is asynchronous as well, which means you have to design it that way. For example it could accept a callback, just like asyncronousFunction
does.
They are not different variables, it is the same variable... but you haven't assigned a value to myVariable
before you return
it at the end of the function.
The correct pattern here would be for getVariable
and asychronousFunction
to accept callbacks, which are executed when the asynchronousFunction
has finished executing.
function getVariable(callback) {
var myVariable;
asyncronousFunction(function(/* pass callback as one of the parameters */){
myVariable = ...
});
// Don't return myVariable, as it's useless at this point
};
function asyncronousFunction(callback) {
// This simulates the asynchronous call. When the call finishes, invoke callback and pass the result as a parameter.
setTimeout(function () {
callback("result");
}, 1000);
}
You should then edit how you use the function getVariable()
.
So where you might have had:
var value = getVariable();
// do whatever with value
value++;
You should now have:
getVariable(function (value) { // value is now passed as a parameter
value++;
});
本文标签: javascriptvariable scope in asynchronous functionStack Overflow
版权声明:本文标题:javascript - variable scope in asynchronous function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741813073a2398912.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论