对异步请求进行回调,当我不想要它时,传递的变量会被覆盖

时间:2013-07-12 18:40:11

标签: javascript asynchronous coffeescript

我目前正在遍历一系列位置对象。然后我打电话到谷歌给我一个该地点的全景图。问题是对此的请求是异步的,所以当实际调用回调时,我传递的位置变量是数组中的最后一个位置。

以下是示例代码和控制台日志输出:

  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

正如您所看到的,在初始循环中,控制台看到了正确的位置,在回调中,它只显示循环中的最后一个。任何人都可以指出我如何解决这个问题的正确方向吗?

1 个答案:

答案 0 :(得分: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(不是那样的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循环的主体移动到单独的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)