0

So I want to put the lat en lng from the get request in an Array, and write that array to output.json. However, when I run this app now, I the order of the lat lon doesnt seem to match the order of the postal codes. How is that so?

var jsonarr = []

app.get('/scrape', function (req, res) {

    for (var i = 0; i < dataset.length; i++) {
        axios.get('https://maps.googleapis.com/maps/api/geocode/json?address=' +
            dataset[i]._id + '+Netherlands&***')
            .then(function (response) {
                var contentlat = (response.data.results[0].geometry.location.lat);
                var contentlon = (response.data.results[0].geometry.location.lng);
                // console.log(lat, lon)
                var json = { lat: "", lon: "" };
                json.lat = contentlat;
                json.lon = contentlon;

                jsonarr.push(json)
                console.log(jsonarr)
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    fs.writeFile('output.json', JSON.stringify(jsonarr), function (err) {
        // console.log('File successfully written! - Check your project directory for the output.json file');
    })

The console does print the filled array. The dataset '_id' are postal codes from an external file

Y_Lakdime
  • 825
  • 2
  • 15
  • 33
  • 5
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jeremy Thille Nov 30 '17 at 16:17
  • So why don't you write the file just after the console.log? – Jeremy Thille Nov 30 '17 at 16:17
  • 1
    The call to `fs.writeFile` happens before your client-side data arrives. You need to use promises, nested callbacks, or something along those lines. – Jared Smith Nov 30 '17 at 16:18
  • Thanks, the file is now written propely, however, the first lat & lng, are not from the first postcal code in the file. – Y_Lakdime Nov 30 '17 at 16:22

0 Answers0