As you can see below I'm nesting them, each one depending on the result of the previous. I think it would be better to just chain them together (just have them sequential) but it takes a while for each result to come back and it's asynchronous. When I call the function, the result isn't loaded yet and it returns undefined. How can I make sure that everything is done in the function before I try to get the results?
<!DOCTYPE html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
/*
To get endpoint
https://api.weather.gov/points/39.7456,-97.0892
To get office, zone, forecast etc from end point
https://api.weather.gov/gridpoints/TOP/31,80
*/
var tLat = 40.985;
var tLon = -71.696;
stationString = getStationFromLatLon(tLat,tLon);
console.log(stationString);
function getStationFromLatLon(theLat,theLon){
theURL = 'https://api.weather.gov/points/' + theLat + "," + theLon;
var obsStationsURL;
var obsStationURL;
// This passes in the lat lons and gets the weather observation stations
$.getJSON(theURL, function(data){
console.log(data);
obsStationsURL = data.properties.observationStations;
console.log(obsStationsURL);
// Get the first obsStation using the obsStations URL
$.getJSON(obsStationsURL, function(data2){
obsStationURL = data2.observationStations[0];
console.log(obsStationURL);
// Get the weather station ID and name using the station URL from previous call
$.getJSON(obsStationURL, function(data3){
stationID = data3.properties.stationIdentifier;
stationName = data3.properties.name;
console.log(stationID + " " + stationName);
returnString = stationID + " " + stationName;
return returnString;
})
});
});
}
</script>
</body>