Reputation: 39
I fetch this array from server :
[{
"res_id": 0,
"res_name": "string",
"res_desc": "string",
"res_address": "string"
},
etc
]
I have to display a list of markers on map, so I map my restos into marker to populate the coords, the first problem is with the data i get from server, its an adress, so then I call:
restos.forEach(x => FetchGeocoder(x.res_address));
To then fetch with geocoder:
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
}
});
};
The problem I cant resolve is that I get 3 coords objects, because I have 3 restos in my array, but only 1 coords object is assigned to all of my restos, instead of each coords beeing asigned to the correct resto.
Thanks in advance for any help or assistance!
Upvotes: 1
Views: 48
Reputation: 30360
One option would be to make use of async/await to perform asynchronous function calls (ie to fetchGeocode()
) during each iteration of the restos
array.
For example, you could adapt your code to use the following (or similar) pattern:
/* 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
}
Usage would then look like this:
// If called inside an async function
await addCoordsToRestos( restos );
Or:
// If called as a promise
addCoordsToRestos( restos ).then(() => { console.log('done') });
Upvotes: 1