变量的 JavaScript 设置值失败

标签 javascript intel-xdk

我是 JavaScript 的新手。我正在尝试使用以下代码将值设置为变量但失败了。有人请帮助指出我的代码有什么问题。

当我尝试打印出变量“deviceLatitude”的值时,它给我“undefined”。但是如果我从函数内部打印值,它会给我正确的值。我做错了什么?

我需要为此值设置全局变量的原因是因为我需要在后期使用它,例如根据需要将距离与不同位置进行比较。

var deviceLatitude;
var deviceLongitude;
function suc (p) {
     deviceLatitude = p.coords.latitude;
     deviceLongitude = p.coords.longitude;
     // alert(deviceLatitude);
}
intel.xdk.geolocation.getCurrentPosition(suc);
alert(deviceLatitude);

最佳答案

suc 被异步回调,所以当您在调用 intel.xdk.... 后发出警报时,suc还没有被调用。

注意文档,我强调的是:

Use this command to get the current location. This command asynchronously acquires the approximate latitude and longitude of the device. When data is available, the success function is called. If there is an error getting position data, the error function is called.

因此,如果您想对 deviceLatitude 执行某些操作,则必须在 回调中执行。

如果你是一个 promise 类型的人,你可以这样做:

function getCurrentPosition() {
  return new Promise(function(resolve, reject) {
    intel.xdk.geolocation.getCurrentPosition(resolve, reject);
  });
}

getCurrentPosition.then(
  function(p) {
    //do something with p.coords.latitude
  },
  function() {
    //something went wrong
  }
 );

关于变量的 JavaScript 设置值失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24843009/

相关文章:

php - 火狐浏览器 : Open XLSX file not saving file butn opening binary

javascript - Facebook javascript api - 应用程序设置不允许一个或多个给定 URL

javascript - 无法使与 javascript 长度相关的正则表达式起作用

javascript - 在没有 HTML DOM 的情况下显示 JavaScript 生成的二维码

rest - 使用 Intel XDK 的 HTTP 基本身份验证

javascript - json 值 javascript XDK

javascript - AngularJS - 使用书签

android - XDK - 如何使用 img 标签从 Android 中的 URL 加载图像

javascript - 英特尔XDK : editor doesn't recognize <script>

html - 英特尔 XDK 是开源的吗?