1

I can console log both results.data.features and results.data.features[0].center when I console results.data.features[0].center it shows the data for the location but when I call it in the .get request it returns undefined. I am not sure what I am doing wrong and any guidance would be a great help!

   router.get('/api/search/:location', async (req, res) => {
    const searchLocation = req.params.location;

    const geocode_res = await geocode(searchLocation, ({ latitude, longitude }) => {
       searchFunction(latitude, longitude)
    })

    console.log(geocode_res)
    res.send(geocode_res)
    
})
    module.exports = {
    async searchFunction(latitude, longitude){
        const URL = `https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&latitude=${latitude}&longitude=${longitude}&maxradiuskm=50`
        try {
            let results = await axios.get(URL)
            return results.data.features
        } catch (err) {
            console.log(`${err}`)
        }
    },

        async geocode(location, callback) {
        try{
            const GEO_URL = `https://api.mapbox.com/geocoding/v5/mapbox.places/${location}.json?access_token=${process.env.MAPBOX_API}`;
            let results = await axios.get(GEO_URL)
            const latLong = results.data.features[0].center
            callback({
                        latitude: latLong[1],
                        longitude: latLong[0]
                    })

        }catch(error){
            console.log(` ${error}`)
        }
    
    },

}

1 Answers1

1

Since searchFunction is an async function, you need to call it with await. And await can only be called inside an async function, thats why you need to make your callback an async function.

Also, you need to do return from the callback

Try this:

const geocode_res = await geocode(searchLocation, async ({ latitude, longitude }) => {
   return await searchFunction(latitude, longitude)
})

You also need to return from your geocode function. so that returned value can be populated in geocode_res

async geocode(location, callback) {
    try{
        const GEO_URL = `https://api.mapbox.com/geocoding/v5/mapbox.places/${location}.json?access_token=${process.env.MAPBOX_API}`;
        let results = await axios.get(GEO_URL)
        const latLong = results.data.features[0].center
        // add return here
        return callback({
                    latitude: latLong[1],
                    longitude: latLong[0]
                })

    }catch(error){
        console.log(` ${error}`)
    }

},
Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52