0

I am currently looping through an array of location objects. I am then calling out to google to get me a panorama for that location. The problem is the request for this is asynchronous, so when the callback actually gets called, the location variable I passed is the last location in the array.

Here is example code, and console log output:

  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          
    )

enter image description here

As you can see, in the initial loop the console sees the correct location, in the callback, it only shows the last one from the loop. Can anyone point me in the right direction on how to fix this?

4

1 回答 1

3

更新:

您应该使用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

ORIGINAL(不那么咖啡脚本,但仍然以咖啡脚本的方式进行):

您需要将代码包装在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循环体移动到单独的function

  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)
于 2013-07-12T18:48:39.967 回答