JS返回值的功能与从其外部返回值不同

时间:2013-02-14 17:25:37

标签: javascript

首先发布在这里!试图修复此问题并在线寻找答案但不是运气 - 我知道它在那里,但似乎无法弄明白 - 我有一个javascript代码返回用户的位置如下:

var myLatlon = navigator.geolocation.getCurrentPosition(onSuccess, onError);

功能如下:

var onSuccess = function(position) {
    var latlon=position.coords.latitude+','+position.coords.longitude;
    return latlon;
};

当我做一个console.log(latlon);在上面的函数内部,它返回以逗号分隔的实际纬度和经度。

但是当我在第一行之后执行console.log(myLatlon)时;它返回: {“timer”:true}

我需要从我的函数返回实际的纬度和经度。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

通常,您无法从用于处理异步执行的回调中返回。必须在回调中调用任何依赖于 返回的值的代码。

这就是异步的工作原理。

答案 1 :(得分:1)

您无法从navigator.geolocation.getCurrentPosition返回值。这就是异步调用的本质。在调用回调之前,对navigator.geolocation.getCurrentPosition的调用结束。您必须在onSuccess回调

中使用您的坐标

通常重组代码与返回代码的效果几乎相同。

navigator.geolocation.getCurrentPosition(function(position){
    // Use position from here
}, onError);
// This line is reached before the commented line in the anonymous function above, that's why you can't return the value
相关问题