javascript - 异步请求回调,传递的变量在我不希望它们被覆盖时被覆盖

标签 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

如您所见,在初始循环中,控制台看到正确的位置,在回调中,它仅显示循环中的最后一个位置。谁能指出我如何解决这个问题的正确方向?

最佳答案

更新:

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

相关文章:

javascript - 从表格中获取表格中的输入值

javascript - 在 Firefox 中打开 IndexedDB 时出现 InvalidStateError

objective-c - 如何从同步转换为异步 NSURLConnection

具有可变参数模板的 C++ 异步无法找到正确的函数模板特化

javascript - 无需 Websocket 即可向浏览器异步推送消息

javascript - 错误 [ERR_REQUIRE_ESM] : require() of ES Module not supported

javascript - 需要一个正则表达式来获取从 # 到非字母表的所有字母

Coffeescript 类共享属性

Heroku -> GitHub SSH key 问题

angularjs - 如何使用 AngularJS 单页应用程序处理页面刷新