Javascript Javascript将回调函数的返回值分配给全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7189492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript assigning the return value of a Callback function to global variable
提问by Serdar Dogruyol
My question is about Javascript. I have a Callback function which receives a Position object on a successful callback.
我的问题是关于 Javascript。我有一个回调函数,它在成功回调时接收一个 Position 对象。
The problem is that when I try to set the properties of the Position object to a global variable at a successful callback it just does not let me do it and the global just remains undefined.
问题是,当我尝试在成功回调时将 Position 对象的属性设置为全局变量时,它只是不允许我这样做,并且全局变量仍然未定义。
As a workaround to that instead of directly setting the object properties to global variables i'm trying to return it through the callback function but I couldn't find a way to set the return value of the callback function to a global variable.
作为一种解决方法,而不是直接将对象属性设置为全局变量,我试图通过回调函数返回它,但我找不到将回调函数的返回值设置为全局变量的方法。
Here's the simplified code.
这是简化的代码。
var x;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
//on Successful callback receives a Position Object
function onSuccess(position) {
var coords = position.coords;
x=coords; // Setting directly to an object does not work x still remains undefined after succesful callback
return coord; // Trying to set this to a global object
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
回答by Felix Kling
You can't return a value from the callback (in this case). That would mean that inside of getCurrentPosition
, the return value from the callback has to be assigned somewhere.
您不能从回调中返回值(在这种情况下)。这意味着在 内部getCurrentPosition
,必须将回调的返回值分配到某个地方。
Assigning it to a global variable works, but at the time you access that variable, it was not assigned the new value yet. E.g.
将它分配给全局变量是可行的,但是在您访问该变量时,它还没有分配新值。例如
// x is assigned in `onSuccess`
var x;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert(x); // will be undefined, the response is not processed yet
Think about it: getCurrentPosition
is probably doing an Ajax request to get the position. Such a request takes (a) time (couple of milliseconds) and because of that (b) is asynchronous, which means that JavaScript does not waituntil the response is received. Your code is wayfaster. onSuccess
was not called yet when you alert x
.
想一想:getCurrentPosition
可能是在做一个 Ajax 请求来获取位置。这样的请求需要 (a) 时间(几毫秒)并且因为 (b) 是异步的,这意味着 JavaScript不会等到收到响应。您的代码的方式更快。onSuccess
当您 alert 时尚未调用x
。
Only solution:
唯一的解决办法:
All the code that has to access the position as to be in or called from the callback.
必须访问位置以在回调中或从回调中调用的所有代码。
回答by HBP
As described by Felix King, you cannot return a value from a callback and in your global variable variant, the variable will not be set until after the AJAX request completes and calls the callback (hence its name !).
正如 Felix King 所描述的那样,您不能从回调中返回值,并且在您的全局变量变体中,直到 AJAX 请求完成并调用回调(因此得名!)之后才会设置该变量。
Using a global variable you can solve your problem if you have some sort of processing loop, you can add this code to that loop to do what is required whenever the coord changes.
如果您有某种处理循环,则可以使用全局变量来解决问题,您可以将此代码添加到该循环中,以便在坐标发生变化时执行所需的操作。
if (coord) // global variable has a new value
// process it
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
// then clear it
coord = null;
}
回答by JavaScripter
You can implement a helper method like flowing:
您可以实现一个辅助方法,如流动:
var LocationHelper = function() {};
LocationHelper.prototype.getLocation = function(callback) {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(pos) {
callback({
pos: pos
});
}
function onError(message) {
callback({
message: message
});
}
};
回答by WickyNilliams
have you tried setting it via the global window
object?
您是否尝试过通过全局window
对象设置它?
//on Successful callback receives a Position Object
function onSuccess(position) {
var coords = position.coords;
window.x=coords; // Setting directly to an object does not work x still remains undefined after succesful callback
return coord; // Trying to set this to a global object
}
also, since you return the coordinates from the success handler, is there not another way to get this value?
此外,由于您从成功处理程序返回坐标,是否没有另一种方法来获取此值?
回答by Baptiste Pernet
put a console.log(x);
just after x=cords
to check the value (works on Chrome and FF with FireBug)
把console.log(x);
刚过x=cords
检查值(在Chrome和FF与萤火作品)
do that also just after the call of OnSuccess.
在 OnSuccess 调用之后也这样做。
Also don't forget that there is asynchronous code in JS (if you use AJAX to get the position), maybe you just don't receive the answer when you check the value of x
还有别忘了JS里面有异步代码(如果你用AJAX来获取位置的话),也许你只是在检查值的时候没有收到答案 x