Javascript将回调函数的返回值分配给全局变量 [英] Javascript assigning the return value of a Callback function to global variable

查看:73
本文介绍了Javascript将回调函数的返回值分配给全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于 Javascript.我有一个回调函数,它在成功回调时接收一个 Position 对象.

My question is about Javascript. I have a Callback function which receives a Position object on a successful callback.

问题是,当我尝试在成功回调时将 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.

作为一种解决方法,而不是直接将对象属性设置为全局变量,我试图通过回调函数返回它,但我找不到将回调函数的返回值设置为全局变量的方法.

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.

这是简化的代码.

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    + '
' +
          'message: ' + error.message + '
');
}

推荐答案

您不能从回调中返回值(在这种情况下).这意味着在 getCurrentPosition 内部,必须将回调的返回值分配到某处.

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.

将其分配给全局变量是可行的,但是在您访问该变量时,它还没有分配新值.例如

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

想一想:getCurrentPosition 可能正在执行 Ajax 请求以获取位置.这样的请求需要 (a) 时间(几毫秒),因此 (b) 是异步,这意味着 JavaScript 不会等待直到收到响应.您的代码方式更快.onSuccess 在您提醒 x 时尚未调用.

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 wait until the response is received. Your code is way faster. onSuccess was not called yet when you alert x.

唯一的解决办法:

必须访问要在回调中或从回调中调用的位置的所有代码.

All the code that has to access the position as to be in or called from the callback.

这篇关于Javascript将回调函数的返回值分配给全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆