I am still new to async functions so I'm still learning. I am trying to use an async function to find the closest station based on specific coordinates. I used the Google Geocoder to find the longitude and latitude of a location from the user and made an API request to Worldtides with the coordinates to find the station. However, when I try to get the closest station's coordinates, longlatResults comes back undefined. Also, longlatResults only comes back undefended the first time. Once I run it again, it works fine. I am not quite sure what I am doing wrong.
Below is the code that throws an error where longlatResults is undefined.
var geo = geocoder({
key: "******************"
})
geo.find(req.body.location, function (err, result) {
const lat = result[0].location.lat;
const lng = result[0].location.lng;
const findLongLat = "https://www.worldtides.info/api/v3?stations&lat=" + lat + "&lon=" + lng + "&stationDistance=50&key=************"
async function getJSON(url) {
const response = await axios.get(url);
return Promise.resolve(response.data.stations);
}
const data = getJSON(findLongLat).catch((error) => {
console.log(error)
})
data.then(async (longlatResults) => {
const newLat = longlatResults[0].lat;
const newLong = longlatResults[0].lon;
})
})