[英]How to implement promises with the HTML5 Geolocation API?
我怎樣才能更正下面的代碼,以便它不返回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);
這個演示使用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
時解析的promise。 我將該函數添加回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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.