javascript - Javascript 数组空不空(Ajax)
问题描述
我正在尝试将 API google 发送给我的地址检索到一个数组中。问题是我刚刚收到一个包含所有元素的数组 empty(Address)。我尝试 async: false 我的 ajax,因为我的第一印象是异步是问题所在,但它什么也没做。如果你有任何想法会很好,谢谢。
输出 :
(4) [Array(0), Array(0), Array(0), Array(0)]
0: Array(0)
id: 9
coord: "Rue des Haies 56, 6001 Charleroi, Belgique"
length: 0
__proto__: Array(0)
1: [id: 10, coord: "43 Rue de Boulainvilliers, 75016 Paris, France"]
2: [id: 11, coord: "Grand Place 22, 7000 Mons, Belgique"]
3: [id: 12, coord: "28 Place Sébastopol, 59000 Lille, France"]
length: 4
__proto__: Array(0)
我的代码:
let geocoder = new google.maps.Geocoder;
$.ajax({
type: "POST",
url: "{{ path('url') }}",
async : false,
success: function (data) {
let positions = JSON.parse(data);
let allAddress = [];
Array.from(positions).map((position, index) => {
allAddress[index] = [];
let latlng = {
lat: parseFloat(position['latitude']),
lng: parseFloat(position['longitude'])
};
let idPosition = position['id'];
geocoder.geocode({'location': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
let searchCoords = results[0]['formatted_address'];
setTimeout(function() {
allAddress[index]['id'] = idPosition;
allAddress[index]['coord'] = searchCoords;
}, 0);
} else {
console.log("Geocode wasn't successful for the following reason : " + status);
}
});
});
console.log(allAddress);
}
});
解决方案
由于地理编码器是异步的,因此您需要使用 Promises 和 Promise all。下面是成功块
let positions = JSON.parse(data);
let allAddress = [];
// array to hold promises
const geoPromises = []
Array.from(positions).map((position, index) => {
allAddress[index] = [];
let latlng = {
lat: parseFloat(position['latitude']),
lng: parseFloat(position['longitude'])
};
let idPosition = position['id'];
// push the promise into our array
geoPromises.push(new Promise(function(resolve, reject) {
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
let searchCoords = results[0]['formatted_address'];
allAddress[index] = {
id: idPosition,
coord: searchCoords,
};
// resolve the promise
resolve(results)
} else {
console.log("Geocode wasn't successful for the following reason : " + status);
// reject it
reject(status)
}
});
}))
});
// wait for all the promises to complete
Promise.all(geoPromises).then(function(values) {
// show your addresses
console.log(allAddress);
}).catch(error => {
console.error(error.message)
});
推荐阅读
- ios - 不透明度仅保持一秒钟
- php - CakePHP 2.4 在单个 Select 查询中为每个事件获取 10 条记录
- android - 通过 USB 在 android studio 中未检测到 Mi A2 手机
- python - Pandas 中的 Vlookup 功能
- php - 模板中的 app.request.method 参数总是在表单提交后给出 GET
- python - Django 多数据库路由。缺少 1 个必需的位置参数:“模型”
- python - 这是一种像在 python 中一样在 R 中使用标头进行授权的方法吗?
- python-3.x - 身份验证时未收到刷新令牌
- css - Firefox 没有显示完整的 CSS 动画,但 Chrome 和 IE 有
- angular - JSON到Angular中的动态HTML表