在回调函数内部更改变量并在外部使用

时间:2018-09-20 04:41:09

标签: javascript callback

假设我有以下代码:

var locations = [];

$.each(data.articles_data, function (index, article) {
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': article.location}, function(results, status) {
        if (status == 'OK') {
            var lat = results[0].geometry.location.lat();
            var lng = results[0].geometry.location.lng();

            locations.push(lat + ' - ' + lng);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
});

if(locations.length > 0) {
    // Unfortunately code never get to this point cause locations array is empty
}

您会看到,最初在$。外部声明的 locations 数组仍然为空,即使我已在geocoder.geocode的回调函数中向其中添加了数据。

有没有一种方法可以使它正常工作?我确实需要在回调内填充位置,然后在外部进行访问。

在此先感谢您的帮助

0 个答案:

没有答案
相关问题