所以我一直在研究 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 数组中的项目数。当然,它应该对每一项进行一次处理。如果删除延迟操作,则一切正常。
真诚感谢您的任何帮助。非常感谢
有两个事实共同作用才能得出这个结果:
将对象写入日志时,写入的是对对象的引用,而不是数据的副本。如果对象在记录后发生更改,日志将显示更改的数据。
在回调函数 for 之前循环已经完成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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)