他们没有什么不同变量,它是同一个变量...但你有没有在函数结束时,你return
之前分配一个值myVariable
。
这里的正确模式是getVariable
和asychronousFunction
接受回调,当asynchronousFunction
完成执行时会执行回调。
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);
}
您应该然后编辑你如何使用功能getVariable()
。
那么,你可能有:
var value = getVariable();
// do whatever with value
value++;
你现在应该有:
getVariable(function (value) { // value is now passed as a parameter
value++;
});