-->

jQuery的推迟在for循环(jquery deferred in for loop)

2019-10-21 22:30发布

所以,我一直在努力的jQuery推迟,但在一个循环中检索数据时,我有麻烦。 递延部分似乎只处理来自最终迭代的数据。 如果只有一个数组中的项目,它也将失败,所以我不知道是怎么回事。

我有不同的城市的名字,我想获得中心坐标为每个城市从谷歌地图的地理编码反向

这里是我的函数,得到的中心坐标:

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数组中的项目数。 当然,应该一次处理每个项目。 如果推迟行动被删除,这一切工作正常。

真诚感谢您的帮助。 这是极大的赞赏

Answer 1:

有两个事实是合作,得到的结果:

  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);

}


文章来源: jquery deferred in for loop