【问题标题】:How to implement promises with the HTML5 Geolocation API?如何使用 HTML5 Geolocation API 实现承诺?
【发布时间】:2016-08-27 23:55:11
【问题描述】:

如何更正下面的代码,使其不返回 getPreciseLocation 函数的 undefined 值?

总而言之,当用户单击#precise-location-prompt 并与浏览器共享位置时,应该有一个 AJAX 调用来获取当前天气。但是目前在用户单击#precise-location-prompt 后,会立即出现undefined 值错误。

// Get weather data for the current location
function getCurrentWeather(coordinates) {
  return $.ajax('http://www.example.com/lat=' + coordinates[0] + '&lon=' + coordinates[1]);
}

// Show weather in DOM
function showCurrentWeather(data) {
  var currentTemperature = data.temperature;
  $('#current-temperature').text(currentTemperature);
}

// Get precise location based via the Geolocation API
function getPreciseLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayPosition, displayError);
  } else {
    console.log("Geolocation is not supported by this browser");
  }
}

// Success function for the Geolocation API
function displayPosition(position) {
  return [position.coords.latitude, position.coords.longitude];
}

// Error function for the Geolocation API
function displayError(error) {
  console.log('Precise location is not available at the moment.');
}

// Promises chain with the AJAX requests
function getWeatherWrapper() {
  return getPreciseLocation().then(function(locationData) {
    return getCurrentWeather(locationData);
    }).then(function(weatherData) {
      return showCurrentWeather(weatherData);
    });
}

// User's interaction with the website
$('#precise-location-prompt').on('click', getWeatherWrapper);

【问题讨论】:

  • 如果displayError 被调用,预期的结果是什么?

标签: javascript jquery ajax api geolocation


【解决方案1】:

此演示使用 JSfiddle AJAX 方法(奇怪的是,它使用了 Mootools)来模拟请求,但您可以替换为 $.ajax 方法。我还用 jQuery 的其余部分替换了该测试的 vanilla JS 事件侦听器和选择器,但是您可以很容易地将它们重新添加到您的代码中。

返回一个在 success 回调中解析的新承诺。

function getCurrentWeather(coordinates) {
  return new Promise(function (resolve, reject) {
    new Request.JSON({
      url: '/echo/json/',
      data: {
        json: JSON.encode({ temperature: 'Too hot!' }),
        delay: 1
      },
      onSuccess: function (response) {
        resolve(response);
      }
    }).send();
  });
}

function showCurrentWeather(data) {
  var temp = document.getElementById('current-temperature');
  temp.textContent = data.temperature;
}

返回一个在调用原始displayPosition 时解决的承诺。我将该功能添加回getPreciseLocation,因为它更容易让它工作。您还可以在此处重新添加您的地理位置检查,以及您认为合适的 reject

function getPreciseLocation() {
  return new Promise(function (resolve, reject) {
    navigator.geolocation.getCurrentPosition(function (position) {
      resolve([position.coords.latitude, position.coords.longitude]);
    });
  });
}

这里我们只是减少代码占用,以使用适当的数据调用相关函数。

function getWeatherWrapper() {
  getPreciseLocation()
    .then(getCurrentWeather)
    .then(showCurrentWeather);
}

var prompt = document.getElementById('precise-location-prompt');
prompt.addEventListener('click', getWeatherWrapper);

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 2017-01-31
    • 2018-11-20
    • 2019-01-21
    • 2020-09-20
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多