在Foreach循环中调用Async方法

Calling Async method inside Foreach loop JS

本文关键字:Async 方法 调用 Foreach 循环      更新时间:2023-09-26

我正试图在foreach循环内对Google Maps进行异步调用。

功能如下:

//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. VehicleId2. 纬度3.经度4. 位置

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

如果有人能帮忙,我很高兴。

这里是异步的问题,

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

 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
    }