【问题标题】:Calling Async method inside Foreach loop JS [duplicate]在 Foreach 循环 JS 中调用异步方法 [重复]
【发布时间】:2014-10-09 04:16:26
【问题描述】:

我正在尝试对 Google 地图进行异步调用以获取 foreach 循环内的地址。

这是函数:

//Function to get address from geographic coordinates
        function getAddress(item) {
            var address = 'Not fetched';
            geocoder = new google.maps.Geocoder();
                var latlng = new google.maps.LatLng(parseFloat(item.Latitude), parseFloat(item.Longitude));
                geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK)
                        address = results[0].formatted_address;
                });
                return address;
        }

这是循环:

 recreateMarkers: function (self, data) {
                        data.vehicleInfo.forEach(function (item) {
                            self.Location= getAddress(item);
                        });
                    }

数据结构: 1.车辆标识 2. 纬度 3. 经度 4. 位置

现在的问题是它为所有车辆提供了相同或未定义的位置。

如果有人可以提供帮助会很高兴。

【问题讨论】:

  • 如果没有循环,这甚至都行不通。

标签: javascript jquery asynchronous closures


【解决方案1】:

这里是异步的问题,

return addressaddress = results[0].formatted_address; 分配谷歌获取地址之前执行,所以你的函数应该是这样的

 function getAddress(item) {
            var address = 'Not fetched';
            geocoder = new google.maps.Geocoder();
                var latlng = new google.maps.LatLng(parseFloat(item.Latitude), parseFloat(item.Longitude));
                geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK)
                        address = results[0].formatted_address;
                        return address; //<= this statement should be here
                });
           // Note return address; should not be here
    }

【讨论】:

  • 我试过这个。仍然显示未定义。
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 2020-07-26
  • 2017-09-06
  • 2019-03-24
  • 2020-09-09
  • 2023-03-11
  • 2012-09-10
  • 2020-10-13
相关资源
最近更新 更多