Javascript 在get请求中调用回调时返回未定义
我可以控制台记录Javascript 在get请求中调用回调时返回未定义,javascript,node.js,api,Javascript,Node.js,Api,我可以控制台记录结果.data.features和结果.data.features[0].center当我控制台结果.data.features[0]时,它显示位置的数据,但当我在.get请求中调用它时,它返回未定义的数据。我不确定我做错了什么,任何指导都会大有裨益 router.get('/api/search/:location', async (req, res) => { const searchLocation = req.params.location;
结果.data.features
和结果.data.features[0].center
当我控制台结果.data.features[0]时,它显示位置的数据,但当我在.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)
})
由于searchFunction
是一个async
函数,因此需要使用wait
调用它。而await
只能在async
函数中调用,这就是为什么您需要将callback
设置为async
函数的原因
此外,您还需要从回调中执行返回
试试这个:
const geocode_res = await geocode(searchLocation, async ({ latitude, longitude }) => {
return await searchFunction(latitude, longitude)
})
您还需要从geocode函数返回。因此,返回的值可以填充到geocode\u 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}`)
}
},
从回调返回不会做任何事情,看看它是如何使用的。不幸的是,我已经尝试了这个方法,但它不起作用,它仍然会返回undefinedSorry,但您还需要在geocode函数中执行return callback()
。我已经更新了我的代码,请尝试一下。谢谢你,@RaviShankarBharti
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}`)
}
},