【发布时间】:2020-03-04 12:55:38
【问题描述】:
我正在尝试将 API google 发送给我的地址检索到一个数组中。问题是我刚收到 一个包含我所有元素的空数组(地址)。 我试图 async: false my 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);
}
});
【问题讨论】:
-
因为 geocoder.geocode 我们是异步的,不知道为什么你有一个 setTimeout 在那里。
-
我想填充数组,但如果数组是异步的,我不能这样做,所以我尝试 setTimeout 我填充的每个元素。不知道够不够清楚...
-
那个 setTimeout 不会对异步添加它做任何事情。问题是您正在循环所有内容并拨打所有电话,而您没有等待所有电话完成。你需要用 promise all 来研究 promise。
-
好的,我会阅读文档并尝试这样做。
-
我有两分钟的时间,所以写了要做什么
标签: javascript php ajax symfony