该演示使用 JSfiddle AJAX 方法(奇怪的是,它使用 Mootools)来模拟请求,但您可以在$.ajax
方法。在这个测试中,我还用普通 JS 事件侦听器和选择器替换了 jQuery 的其余部分,但您可以非常轻松地将它们添加回您的代码中。
返回一个新的承诺,该承诺在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 https://jsfiddle.net/4a59k1tz/11/