I've written a piece of code to gather the coordinates of some US cities from an API.
Basically:
- I have a big array (data) with some info on companies, organised by the US state they're located in
- I create an empty array called coords
- I iterate through my big array where all the data is to find the unique cities in each state
- for each city, I fetch the coordinates from an API and push that in my array coords
- After the loop, I console.log the coords array, and it works.
Shouldn't the console.log(coords) just display an empty array?
When I try to do anything else (e.g. JSON.stringify), I get an empty array (probably beacause the after-loop code is executing before the promises resolve? But then why not console.log?)
Can someone explain this weird behavior to me?
// const data = ...allmydata...
let coords = []
const key = 'MYKEY'
for(let state in data){
coords[state] = []
// get the list of unique cities
let cities = [...new Set( data[state].map( x => x['Largest Location'] ) )]
// this is the fetching loop: for each city name
// I'm getting the coordinates asynchronously
cities.forEach( (city) => {
coords[state][city] = {
lat: undefined,
lng: undefined
}
let req = `http://open.mapquestapi.com/geocoding/v1/address?key=${key}&location=${city},${state}`
fetch(req)
.then( res => res.json() )
.then( res => {
coords[state][city]['lat'] = res.results[0].locations[0].latLng.lat
coords[state][city]['lng'] = res.results[0].locations[0].latLng.lng
})
.catch( err => console.log(err) )
})
}
// out of the loop
// this displays my array nicely structured in the console
console.log(coords)
// this displays []
console.log(coords.map(x => x))
// this displays []
console.log(JSON.stringify(coords))
I don't think it's a duplicate from all the questions about why values are undefined in async code (which I've read a fair share), this time the value looks defined where it shouldn't IMHO.
Thanks in advance