我从服务器获取这个数组:
[{
"res_id": 0,
"res_name": "string",
"res_desc": "string",
"res_address": "string"
},
etc
]
我必须在 map 上显示标记列表,所以我将我的餐厅映射到标记中以填充坐标,第一个问题是我从服务器获取的数据,它是一个地址,所以我调用:
restos.forEach(x => FetchGeocoder(x.res_address));
然后使用地理编码器获取:
const FetchGeocoder = async (address) => {
const response = await fetch('https://maps.googleapis.com/maps/api/geocode/json?address=' +
address + ',' +
'CABA&key=' + "KEY")
const responseData = await response.json();
const markers = responseData.results[0].geometry.location;
restos.forEach(x => {
x.res_coords = {
latitude: markers.lat,
longitude: markers.lng
}
});
};
我无法解决的问题是我得到了 3 个坐标对象,因为我的数组中有 3 个恢复对象,但只有 1 个坐标对象分配给了我所有的恢复对象,而不是每个坐标都分配给了正确的恢复对象。
在此先感谢您的帮助或帮助!
最佳答案
一个选择是使用 async/await在 restos
数组的每次迭代期间执行异步函数调用(即 fetchGeocode()
)。
例如,您可以调整代码以使用以下(或类似)模式:
/* Define async fetchGeocode() function that returns lat/lng data */
const fetchGeocode = async (address) => {
const res = await fetch('https://maps.googleapis.com/maps/api/geocode/json' +
'?address=' + address + ',CABA&key=' + API_KEY);
const json = await res.json();
const { lat, lng } = json.results[0].geometry.location;
return {
latitude: lat,
longitude: lng
};
};
// Async function adds coords to each resto
async function addCoordsToRestos(restos) => {
// If restos undefined, or not an iterable array type then return
// an empty array as a default response
if(!Array.isArray(restos)) {
return [];
}
// Iterate each resto
for (const resto of restos) {
// Mutate current resto by adding res_coords. Call fetchGeocode()
// with await to wait for async function to complete before next
// iteration
resto.res_coords = await fetchGeocode(resto.res_address);
}
// Return mutated restos array to next handler
return restos
}
用法看起来像这样:
// If called inside an async function
await addCoordsToRestos( restos );
或者:
// If called as a promise
addCoordsToRestos( restos ).then(() => { console.log('done') });
关于javascript - 如何将对象分配给数组中的正确对象? react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262105/