0

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!')
});
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Y_Lakdime
  • 825
  • 2
  • 15
  • 33
  • 1
    Because you put asynchronous calls into your loop. So your loop will be be done before you hit the first `console.log` inside `.then(...)`. Since `i` is `5` at the time all of these functions are called is the reason why you see this happen. – Spencer Wieczorek Nov 30 '17 at 21:57
  • How can I turn this into a synchronous mechanism then for it to work? – Y_Lakdime Nov 30 '17 at 22:00
  • Possible duplicate of [Calling an asynchronous function within a for loop in JavaScript](https://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript) – Spencer Wieczorek Nov 30 '17 at 22:02
  • How can I turn this into a synchronous mechanism ? ... Using brackets you do blocks that executes synchronously – Mikel Oct 05 '19 at 16:11

0 Answers0