I have a very weird piece of behavior happening. I have a csv file which I need to geocode. It has 250 lines. Google geocoding api has a rate limit per second so I can't just write a for loop over each row. I've elected to use an interval. Every fraction of a second I send off the api request and when finished the results should be written to a new csv file. However no matter what I do I keep only getting 247 results.
In an effort to see where the break was happening I set a called
variable to see how many time my geocoding function was being called. It is indeed being called 250 times. Then I started moving the called
variable deeper into the function callback to see if that was hit 250 times. The weird part is that it is and it isn't.
If I include the increase in called
right after the error check it's 250, but if I put it below the push
statement it's 247.
let called = 0;
/*Handles geocoding via google api*/
function geoCode(obj){
console.log(`${rows.length} items remaining`);
processing += 1;
try {
googleMapsClient.geocode({
address: `${obj.ST_ADDRESS} ${obj.CITY} ${obj.STATE} ${obj.ZIP_CODE} ${obj.COUNTRY}`
}, function(err, response) {
if (!err) {
called +=1; <------------HERE IT'S 250
processing -= 1;
const result = obj;
result.LATITUDE = response.json.results[0].geometry.location.lat;
result.LONGITUDE = response.json.results[0].geometry.location.lng;
results.push(result);
called +=1; <-----------------HERE IT'S 247
if(rows.length < 1 && processing === 0){
// begin writing to file
writeFile(results);
console.log('called', called);
}
}else{
console.log(err);
}
});
}catch (e) {
console.log(e);
}
}
/* Loop through results at sustained pace to prevent rate limiting */
function locationLoop(){
interval = setInterval(()=>{
if(rows.length > 0){
geoCode(rows.shift());
}else{
clearInterval(interval);
}
}, 50);
}