简体   繁体   English

jQuery when()似乎不适用于each()

[英]jQuery when() doesn't seem to be working for each()

In the following code, it seems like the code inside of when() is still executing before the loop has finished. 在下面的代码中,似乎在循环完成之前when()内部的代码仍在执行。 The log statement i have in the loop goes in after the one in the when statement. 我在循环中的log语句在when语句中的一个之后。 The code is not finishing the loop before executing what's in the when statement resulting in an empty array in my when. 代码在执行when语句中的内容之前未完成循环,导致my 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
        });

     });
  });
}

$.when works on deferred objects such as object returned by $.ajax call and not on an Array of Objects $.when适用于延迟的对象,例如$.ajax调用返回的对象,而不适用于Objects Array

You don't seem to have fully understand what $.when does. 您似乎并不完全了解$.when含义。

KNOW MORE ABOUT IT! 了解更多关于它!

In your case this should work, 在您的情况下,这应该可行

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

$.when expects deferred objects. $.when期望延迟的对象。

You should do something like: 您应该执行以下操作:

$.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());
 });

Then, you can do: 然后,您可以执行以下操作:

$.when.apply($, markers).then(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM