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

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

问题描述

我的问题是关于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    + '\n' +
          'message: ' + error.message + '\n');
}


推荐答案

您无法返回回调中的值(在这种情况下)。这意味着必须在 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 在收到响应之前不会等待。您的代码的运行速度更快。提醒 x 时,尚未调用 onSuccess

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将Callback函数的返回值分配给全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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