javascript - jquery在for循环中延迟

标签 javascript jquery google-maps jquery-deferred

所以我一直在研究jquery deferred,但是在循环中检索数据时遇到了麻烦。延迟部分似乎只处理最终迭代中的数据。如果数组中只有一项,它也会失败,所以我不确定发生了什么。

我有多个城市名称,我正在尝试从谷歌地图反向地理编码中获取每个城市的中心坐标

这是我获取中心坐标的函数:

function getGroupLatLng(groupname){
    var deferred = new $.Deferred();

     geocoder.geocode( { 'address': groupname}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
              deferred.resolve(results);

          alert(results[0].geometry.location.lat());
      } else {

      }

    });
    return deferred.promise();
}

这是调用函数的地方,返回结果后会附加一个 div:

var newGroupsLength = newGroups.length;

for (i = 0; i < newGroupsLength; i++) {

    newGroups[i]['counter']=counter;
    var locationName = newGroups[i]['name'];
    counter++;
    alert(locationName);
    $.when(getGroupLatLng(locationName)).then(function(results){
        alert("lat = "+results[0].geometry.location.lat());
        var lat=results[0].geometry.location.lat();
        var lng=results[0].geometry.location.lng();
        console.log(newGroups[i]); //this is running the proper number of times, but it logs the results from the final looped item, 'n' number of times. 

        newGroups[i]['lat']=lat;
        newGroups[i]['lng']=lng;

        var jsonArray=[];
        jsonArray = newGroups[i];
        var template = $('#groupsTemplate').html();
        var html = Mustache.to_html(template, jsonArray);
        $('#groups-container').append(html);
    });
}

我遇到的问题是,延迟循环似乎处理了 for 循环中的最后一个项目“n”次,其中“n”是 newGroupsLength 数组中的项目数。当然,它应该对每一项进行一次处理。如果删除延迟操作,则一切正常。

真诚感谢您的帮助。非常感谢

最佳答案

有两个事实共同作用才能产生该结果:

  1. 将对象写入日志时,写入的是对对象的引用,而不是数据的副本。如果对象在记录后发生变化,日志将显示变化的数据。

  2. 在第一次调用 then 的回调函数之前,循环已经完成。这意味着 i 对于所有回调都将具有相同的值,因此您将所有结果放入同一个对象中。

因此,newGroups[i] 中的值将针对处理的每个响应而更改,但您只会看到日志中的最后一个值,因为这是日志记录时对象包含的内容显示它。

要使循环中的每次迭代都保留 i 的值以供稍后响应到达时使用,您可以使用 IIFE(立即调用函数表达式)为每次迭代创建一个局部变量:

var newGroupsLength = newGroups.length;

for (i = 0; i < newGroupsLength; i++) {

  (function(i){

    newGroups[i]['counter']=counter;
    var locationName = newGroups[i]['name'];
    counter++;
    alert(locationName);
    $.when(getGroupLatLng(locationName)).then(function(results){
        alert("lat = "+results[0].geometry.location.lat());
        var lat=results[0].geometry.location.lat();
        var lng=results[0].geometry.location.lng();

        newGroups[i]['lat']=lat;
        newGroups[i]['lng']=lng;

        console.log(newGroups[i]); // log the object after setting the values

        var jsonArray=[];
        jsonArray = newGroups[i];
        var template = $('#groupsTemplate').html();
        var html = Mustache.to_html(template, jsonArray);
        $('#groups-container').append(html);
    });

  })(i);

}

关于javascript - jquery在for循环中延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28552302/

相关文章:

javascript - 如何将 ES6、AMD 和 CJS 模块与 JSPM 和系统 js 一起使用?

javascript - 使用 JavaScript 从 URL 检查 YouTube 上的视频是否可用

javascript - 使用/编辑和保存按钮在多个输入字段上提交 AJAX

javascript - 抓取图像高度并将其设置为其容器 jquery

javascript - Ajax 成功函数未使用 require 指令调用

Android 谷歌地图自定义标记

android - 如何在android中移动谷歌地图缩放控制位置?

javascript - 为什么我的函数总是返回相同的值?

javascript - 获取 JSON 格式的 Google Map KML 数据

javascript - 简单 PHP 到 Ajax 'not logged in' 错误 - 如何解决?