我当前正在循环访问位置对象数组。然后我调用谷歌,让我得到那个位置的全景图。问题是对此的请求是异步的,因此当回调实际被调用时,我传递的位置变量是数组中的最后一个位置。
这里是示例代码和控制台日志输出:
for location in paginated_data.locations
console.log location
latLng = new google.maps.LatLng(location.latitude,location.longitude)
@sv.getPanoramaByLocation(latLng, 50, (StreetViewPanoramaData, StreetViewStatus) =>
console.log location
)
如您所见,在初始循环中,控制台看到正确的位置,在回调中,它仅显示循环中的最后一个位置。谁能指出我如何解决这个问题的正确方向?
最佳答案
更新:
您应该使用 do
关键字让 CoffeeScript 为每个循环迭代创建一个单独的闭包:
for location in paginated_data.locations
do (location) ->
console.log location
latLng = new google.maps.LatLng(location.latitude,location.longitude)
@sv.getPanoramaByLocation(latLng, 50, (StreetViewPanoramaData, StreetViewStatus) =>
console.log location
原始(不那么 CoffeeScript ,但仍然采用 CoffeeScript 的方式):
您需要将代码包装在 iife 中这样它就有自己的作用域并传入 location
:
for location in paginated_data.locations
((location) ->
console.log location
latLng = new google.maps.LatLng(location.latitude,location.longitude)
@sv.getPanoramaByLocation(latLng, 50, (StreetViewPanoramaData, StreetViewStatus) =>
console.log location
)(location)
或将 for
循环体移至单独的函数
getLocation = (location) ->
console.log location
latLng = new google.maps.LatLng(location.latitude,location.longitude)
@sv.getPanoramaByLocation(latLng, 50, (StreetViewPanoramaData, StreetViewStatus) =>
console.log location
for location in paginated_data.locations
getLocation(location)
关于javascript - 异步请求回调,传递的变量在我不希望它们被覆盖时被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17621868/