0
我正在使用google地理编码api来循环和地理编码22个邮编列表并将它们存储到数据库中。我希望在地理编码完成时显示一条消息,但是由于我必须使用setTimeout来避免在11个邮政编码处遇到“OVER_QUERY_LIMIT”错误,所以我的邮件比实际需要的邮件出现速度要快得多。我该如何解决这个问题?如何在涉及setTimeout的循环完成后显示消息?
JS
function geocodeAddress (postcode) {
geocoder.geocode({'address': postcode}, function(results, status) {
if (status === 'OK') {
var x,
resultsLength = results.length;
for(x = 0; x < resultsLength; x++) {
lat = results[x].geometry.location.lat().toFixed(8);
lng = results[x].geometry.location.lng().toFixed(8);
//send values to php file
sendLatLng(lat, lng);
}
}
else if (status == 'OVER_QUERY_LIMIT') {
//call function again after delay when error is encountered
setTimeout(function() {
geocodeAddress(postcode);
}, 200);
}
else {
console.log('Geocode was not successful: ' + status);
}
});
};
for (n = 0; n < pstcodeLength; n++) {
geocodeAddress(postcodes[n]);
//display message after loop is complete
if (n === pstcodeLength-1) {
console.log('geocoding is complete');
}
}
您是说“地理编码已完成”发生得太快?当然,因为循环完成时异步请求仍在运行。 – epascarello
是的,我知道,一切完成后是否可以显示? – Sai
SO记录完成的每一个,当你达到最大值时,显示消息。 – epascarello