Home > Software engineering >  Async function results undefined
Async function results undefined

Time:09-17

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;
        })
    })

CodePudding user response:

Async functions always return a promise implicitly.

You don't need to explicitly return a promise in getJSON(), because the async keyword will convert whatever you return into a promise automatically.

I'm fairly certain your code is returning a promise that returns a promise which returns the data right now, which is why you can't access any properties of the data outside the method.

You should be able to change the line to this:

return response.data.stations;

CodePudding user response:

Your code is not working properly because you are not ,,waiting" for the response. Instead you are using the promise.

        const data = await getJSON(findLongLat).catch((error) => {
                console.log(error)
        })

This should work

  • Related