Whenever the page starts and my function getWeather calls itself, I feel like it is not considering my $.when(getWeatherData()) .done call. getWeatherData returns itself, but it does not consider the thisUrl var and my getWeather .fails instead. However, if I run the code in debug mode it passes my promise getWeather Data and works as intended.
Am I making and implementing this promise incorrectly? And if this promise function is not going to work with the variables above the return, is there a better way to call this promise and still be able to concatenate my geoposition call?
I also considered maybe returning an $.ajax ({beforeSend: … }) however I don’t see how I would be able to concatenate all the data that I need into the url.
On a side note, I feel like my problem is me not understanding Asynchronous and promises. But I am under the impression that making this promise function and calling it with the $.when object method guarantees that the entire promise function would run from start to finish.
$(document).ready(function(){
var $temp = $("#temp");
var $tempSymb = $("#tempSymb");
getWeatherData = function(){
var pos = {};
navigator.geolocation.getCurrentPosition(function(position) {
pos.lat = position.coords.latitude;
pos.lon = position.coords.longitude;
});
var key = "###";
var thisUrl = 'https://api.wunderground.com/api/' + key + '/conditions/q/' + pos.lat + ',' + pos.lon + '.json'
return $.getJSON(thisUrl);
}
var getWeather = function () {
$.when(getWeatherData())
.done(function(weather){
var thisWeather = weather;
console.log(thisWeather);
var tempF = thisWeather.current_observation.temp_f;
var tempC = thisWeather.current_observation.temp_c;
$("#location").text(thisWeather.current_observation.display_location.city);
$temp.text(tempF);
$("#img").attr("src", thisWeather.current_observation.icon_url);
$("#dateTime").text(thisWeather.current_observation.local_time_rfc822);
})
.fail(function(){
alert("Unable to get weather");
});
}();
});
<!-- language: lang-html -->
<div class="container">
<div class="row">
<div id="forecast">
<h1>Weather at <span id="location"> </span></h1>
<div id="imgdiv">
<img id="img" src=""/>
</div>
<p>It is currently <button class="btn btn-primary"><span id="temp"> </span><span id="tempSymb">°F</span></button> with <span id="desc"> </span></p>
<p>Wind: <span id="wind"></span></p>
<p>Current Time/Date: <span id="dateTime"></span></p>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>