我编写了一段代码,以通过API收集美国一些城市的坐标。
基本上:
console.log(coords)是否仅显示一个空数组?
当我尝试做其他事情(例如JSON.stringify)时,我得到一个空数组(可能是因为在答应解决之前执行了循环后代码?但是为什么不使用console.log?)
有人可以向我解释这种奇怪的行为吗?
// 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))
我不认为这是关于为什么在异步代码中未定义值的所有问题的重复(我已经读过相当多的内容),这一次该值看起来已定义在不应恕我直言的位置。
预先感谢
答案 0 :(得分:1)
为了确保我做对了,我在Firefox中进行了查看。
我相信正在发生的事情是,您正在记录阵列,但当时它仍然为空。
但是,使用今天更好的控制台,至少在firefox中,我不仅获得了变量,还获得了对该变量的引用。
结果输入后,将现有变量添加到其中。当我单击小“扩展”三角形时,实际上我注意到可以看到记录后添加的空数组中的数据。