简体   繁体   English

forJSON中的getJSON之后的回调

[英]callback after getJSON in for loop

So i'm doing a getJSON request in a for loop. 所以我在for循环中执行getJSON请求。 In the getJSON function callback I push the values into a global array. 在getJSON函数回调中,我将值推送到全局数组中。

Now accessing that global array outside the for loop is not possible due the fact getJSON is async i read... 现在无法访问for循环之外的全局数组,因为我读取了getJSON是异步的事实...

I tried making flags and other callback functions but it looks like even the for loop ends faster (even with je getJSON function insde the for loop) than the getJSON requests.. 我试着制作标志和其他回调函数,但是看起来for循环的结束(即使使用je getJSON函数insde for循环)也比getJSON请求更快。

function initMap(){

// Address value variables
var country;
var city;
var addresses = [];
var locations = [];

// Google maps variables
var myOptions = {
    zoom: 5,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: 'terrain',
    scrollwheel: false,
    navigationControl: true,
    mapTypeControl: true,
    scaleControl: true,
    draggable: true
};
var marker;
var bounds = new google.maps.LatLngBounds();

// Get country city values
$('li.deal-itinerary-item').each(function(){
    country = $(this).data('country');
    city = $(this).data('city');
    if( country && city ){
        addresses.push(country + ' ' + city);
    }
});

var map = new google.maps.Map($('#map_canvas')[0], myOptions);

for (var x = 0; x < addresses.length; x++) {

    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {

        var p = data.results[0].geometry.location;
        var latlng = new google.maps.LatLng(p.lat, p.lng);

        locations.push({lat: p.lat, lng: p.lng});

        marker = new google.maps.Marker({
            position: latlng,
            map: map
        });

        bounds.extend(marker.position);

    });

}

// CONSOLE LOG NOT WORKING HERE
console.log(locations);

map.fitBounds(bounds);

zoomChangeBoundsListener = 
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
    if (this.getZoom()){
        this.setZoom(6);
    }
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);

};
google.maps.event.addDomListener(window, 'load', initMap);

So first the variables, then i get Country name and City name out of data attribute on divs inside the dom. 因此,首先使用变量,然后从dom内div上的数据属性中获取“国家名称”和“城市名称”。 Then I itterate over the addresses to get the lat/lng values for the markers (and the polylines). 然后我遍历地址以获取标记(和折线)的lat / lng值。 If i console.log the locations variable at the end, it shows an empty array in the console, but when I click the array is filled (probably cause the array gets filled after displaying it).. 如果我在console.log末尾的locations变量中,它在控制台中显示一个空数组,但是当我单击该数组时已填充(可能导致该数组在显示后被填充)。

PS Since I can't yet post images, the console.log() displays just [ ] and when i click on the array it show the objects just fine... PS由于我还不能发布图像,所以console.log()仅显示[],当我单击数组时,它可以很好地显示对象...

0  Object { lat=53.3498053,  lng=-6.2603097}
1  Object { lat=53.3498053,  lng=-6.2603097}
2  Object { lat=53.3498053,  lng=-6.2603097}
3  Object { lat=53.717856,  lng=-6.3560985}
4  Object { lat=54.5982897,  lng=-5.8925882}
5  Object { lat=53.59944249999999,  lng=-7.850193999999999}
6  Object { lat=54.6541972,  lng=-8.110546}
7  Object { lat=54.9558392,  lng=-7.7342787}

Any help on this is highly appriciated since im stuck on this since yesterday... 自从昨天以来我一直对此坚持不懈,对此提供了任何帮助。

Try: 尝试:

var count_getJSONs_done = 0;
for (var x = 0; x < addresses.length; x++) {

    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {

        var p = data.results[0].geometry.location;
        var latlng = new google.maps.LatLng(p.lat, p.lng);

        locations.push({lat: p.lat, lng: p.lng});

        marker = new google.maps.Marker({
            position: latlng,
            map: map
        });

        bounds.extend(marker.position);

    })
      .always(function() {
         count_getJSONs_done++;
         if (count_getJSONs_done == addresses.length) // the last getJSON in the loop is completed
           processLocations();
      });

}

According to http://api.jquery.com/jquery.ajax/ , section: "Callback Function Queues", the .always callback will be invoked after success handler of getJSON . 根据http://api.jquery.com/jquery.ajax/中的 “回调函数队列”部分,将在getJSON success处理程序之后调用.always回调。

Updated: Notice, that this code works even if some of the getJSON have failed. 更新:请注意,即使某些getJSON失败,此代码也可以工作。

Try this logic 试试这个逻辑

for (var x = 0; x < addresses.length; x++) {

$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {

    var p = data.results[0].geometry.location;
    var latlng = new google.maps.LatLng(p.lat, p.lng);

    locations.push({lat: p.lat, lng: p.lng});

    marker = new google.maps.Marker({
        position: latlng,
        map: map
    });

    bounds.extend(marker.position);

    if(locations.length == addresses.length){ // all locations gathered
        console.dir(locations)
    }
});

} }

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

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