【发布时间】:2020-01-11 18:39:42
【问题描述】:
最终结果打算存储在下面的locations数组中。
const locations = []
我创建了一个接受location 参数的异步函数,然后locationSearch 将使用该参数向Google Places 发出GET 请求。
const locationSearch = await (
axios.get(`https://maps.googleapis.com/maps/api/place/textsearch/json?query=${location}`, {json: true})
.then(response => {
if(response.data.results.length < 1) throw new Error('Unable to find location.')
return response.data.results
}).catch(error => {
return error
})
)
结果返回一个地点数组,然后我会将其传递给locationSearch 以使用place_id 获取更多详细信息。
const locationDetails = await locationSearch.map(async (locationData) => {
const { place_id: id } = locationData
await (
axios.get(`https://maps.googleapis.com/maps/api/place/details/json?placeid=${id}`, {json: true})
.then(locationDetails => {
if(locationDetails.data.result.length === 0) throw new Error('Unable to find location ID!')
const { name, geometry, types, photos, rating, user_ratings_total, opening_hours, icon, formatted_address, formatted_phone_number, price_level, reviews } = locationDetails.data.result
locations.push({
latitude: geometry.location.lat,
longitude: geometry.location.lng,
types,
reviews,
photos,
rating,
user_ratings_total,
opening_hours,
icon,
name,
location: formatted_address,
formatted_phone_number,
price_level
})
}).catch(error => {
return error
})
)
})
但是,我不确定应该在哪里返回位置,因为locationDetails 仅用于将结果映射到locations。解析后的 Promise 返回如下:
return Promise.all(locationSearch, locationDetails)
我希望这个问题不会让人觉得很愚蠢。此外,任何关于编写代码错误的反馈或指示都将不胜感激!
【问题讨论】:
标签: javascript promise async-await axios