在下面的代码中,似乎while()内部的代码在循环完成之前仍在执行。我在循环中的日志语句在when语句中的日志语句之后进入。在执行when语句中的内容之前,代码没有完成循环,导致我的when中出现空数组。
function LocationsForState(state) {
console.log(state);
$.ajax({
url: '/Home/GetApartmentsForStateJSON?state=' + state
})
.done(function (apartments) {
//set up markers
var markers = [];
var geocoder = new google.maps.Geocoder();
$.each(apartments, function (index, apartment) {
var address = apartment.Address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
markers.push({ "latitude": latitude, "longitude": longitude, "icon": "../../Content/img/mapMarker.png", "baloon_text": 'This is <strong>Texas</strong>' });
console.log('In loop' + markers);
}
});
});
$.when(markers).then(function () {
console.log('In when' + markers);
var myMarkers = { "markers": [markers] };
//set up map options
locationMap.mapmarker({
zoom: 6,
center: 'United States/' + state,
markers: myMarkers
});
});
});
}
答案 0 :(得分:2)
答案 1 :(得分:2)
在你的情况下这应该有效,
function LocationsForState(state) {
console.log(state);
$.ajax({
url: '/Home/GetApartmentsForStateJSON?state=' + state
}).done(function (apartments) {
//set up markers
var markers = [];
var defs = [];
var geocoder = new google.maps.Geocoder();
$.each(apartments, function (index, apartment) {
var address = apartment.Address;
var deferred = $.Deferred();
defs.push(deferred.promise());
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
markers.push({
"latitude": latitude,
"longitude": longitude,
"icon": "../../Content/img/mapMarker.png",
"baloon_text": 'This is <strong>Texas</strong>'
});
console.log('In loop' + markers);
deferred.resolve();
}
});
});
$.when.apply($, defs).then(function () {
console.log('In when' + markers);
var myMarkers = {
"markers": [markers]
};
//set up map options
locationMap.mapmarker({
zoom: 6,
center: 'United States/' + state,
markers: myMarkers
});
});
});
}
答案 2 :(得分:0)
$.when
期待延期对象。
您应该执行以下操作:
$.each(apartments, function (index, apartment) {
var address = apartment.Address;
// create the deferred object
var deferred = $.Deferred();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
// resolve the deferred when request is complete
deferred.resolve({
"latitude": latitude,
"longitude": longitude,
"icon": "../../Content/img/mapMarker.png",
"baloon_text": 'This is <strong>Texas</strong>'
});
console.log('In loop' + markers);
}
});
// add promise to markers
markers.push(deferred.promise());
});
然后,你可以这样做:
$.when.apply($, markers).then(...)