So I want to loop through postal codes from a JSON file in order to geolocate them into lat&lon. However, the code after the get() function seems to be always picking the last i element in the loop. The console.log(dataset[i]._id) produces five times the postcal code of the fith element. How does that come?
var jsonarr = []
app.get('/scrape', function(req, res){
for(var i = 0; i < 5; i++) {
var aantallen = dataset[i].count
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address=' +
dataset[i]._id + '+Netherlands&key=*')
.then(function (response) {
// console.log(i)
var contentlat = (response.data.results[0].geometry.location.lat);
var contentlon = (response.data.results[0].geometry.location.lng);
var json = {lat: "", lon: "", aantal: ""};
json.lat = contentlat;
json.lon = contentlon;
json.aantal= aantallen;
console.log(dataset[i]._id)
jsonarr.push(json)
fs.writeFile('output.json', JSON.stringify(jsonarr, null, 4), function(err){
// console.log('File successfully written! - Check your project directory for the output.json file');
})
})
.catch(function (error) {
console.log(error);
});
}
res.send('Check your console!')
});