在Foreach循环中调用Async方法
Calling Async method inside Foreach loop JS
我正试图在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 address
在address = 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
}
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 什么'这是从第三个函数上的async 1st函数获得结果的更好方法
- async.js在使用瀑布方法时返回最后一个值
- express js中的async.waterfall方法
- 我怎么能像调用synch方法一样调用async方法呢
- 如何将嵌套_.each转换为同步方法?首选使用 Promise 或 Async.waterfall
- 方法在 async.waterfall 中不起作用
- 使用async方法在数组中循环只获取angular 2中的最后一个元素(ecma6)
- 在Foreach循环中调用Async方法
- 在CefSharp中调用JS中的async方法
- Backbonejs只有在传入async:false作为fetch()方法的参数时才会获取值
- XMLHttpRequest上async属性的javascript默认值是什么?开放的方法
- async模块内部类的访问方法或
- 在Spring MVC中返回@Async方法结果,并将其返回给Ajax客户端
- 我使用Async's库并行方法错误?但如何
- 当调用mongoose save方法时,async.js的瀑布方法会挂起
- jQuery如何在$.ajax方法中实现async:false
- Jquery中是否有async:false的替代方法?
- Async Javascript uncatch TypeError:对象没有方法“test”
- 在async方法完成之前返回的函数