亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在獲取請求中調用時,回調返回未定義

在獲取請求中調用時,回調返回未定義

明月笑刀無情 2023-08-05 19:27:41
我可以控制臺記錄兩者results.data.features,results.data.features[0].center當我控制臺時,results.data.features[0].center它顯示該位置的數據,但是當我在.get請求中調用它時,它返回未定義。我不確定我做錯了什么,任何指導都會有很大的幫助!   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 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

由于searchFunction是一個async函數,因此您需要使用 來調用它await。并且await只能在async函數內部調用,這就是為什么你需要創建callback一個async函數。


return另外,您需要從回調中執行


嘗試這個:


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

   return await searchFunction(latitude, longitude)

})

您還需要從地理編碼函數返回。以便可以將返回值填充到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}`)

    }


},


查看完整回答
反對 回復 2023-08-05
  • 1 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號