-1
I’m using a Google API, and I need for the request part to wait for at least 3 seconds before making another request, I tried to do this, but could not, setTimeOut does not wait 3 seconds!.
function getLatLong(polos, res) {
polos.forEach(element => {
setTimeout(() => {
request({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=' + element.endereco + ' - ' + element.cep + ' - BRASIL' + '&key=AIzaSyCh2Y3mfj2uJtXBHoYeAWvwyHvYCN0iKlk',
json: true
}, function (error, response, data) {
if (data["results"][0]) {
console.log(data["results"][0].geometry["location"]);
}else {
console.log("Não pegou", element.nome)
return false;
}
// res.send(data);
// var latLong = (data["results"][0].geometry["location"]);
// console.log(latLong);
});
}, 3000);
});
}
Console output :
{ lat: -29.6871895, lng: -53.8090582 }
{ lat: -23.4391891, lng: -51.9142814 }
{ lat: -23.1814106, lng: -50.6480145 }
Não pegou ASTORGA - PR
Não pegou POÇOS DE CALDAS - MG
Não pegou SALVADOR - BA
Não pegou GOIOERÊ - PR
{ lat: -20.4557007, lng: -54.5936527 }
{ lat: -26.9205582, lng: -49.0696077 }
Não pegou CAMPO MOURÃO - PR
{ lat: -27.5991936, lng: -48.6084431 }
Não pegou PATROCÍNIO - MG
Não pegou SUZANO - SP
Não pegou PORECATU - PR
{ lat: -22.5292946, lng: -52.1804526 }
{ lat: -10.1870213, lng: -48.3282553 }
Não pegou LAGES - SC
{ lat: -26.488296, lng: -49.0828988 }
{ lat: -16.4696391, lng: -54.6311907 }
{ lat: -23.3034209, lng: -51.1419351 }
Não pegou OLINDA - PE
{ lat: -24.9553923, lng: -53.4575696 }
{ lat: -19.9689819, lng: -44.2008435 }
Não pegou RIO DE JANEIRO - TIJUCA - RJ
The problem is he’s not waiting 3 seconds before making another request. What could I do?
It worked! , but is there no other way, I do it because the api does not let me make one request after another, there is some other way?
– Felipe Oliveira
you can use Timer, but the code would be harder to understand. The best solution in my opinion is to call the next request, after the previous one is closed (recursively).
– Sveen