0

While converting the locations, I want to create an object as lats and longs such as {"lat":123123, "lng" : 12324} of the actual location and immediately store it into coordinates array. However, at the end, when I check the coordinates array, it is shown as an empty array. Is it because the coordinates.push({"lat" : lat, "lng": lng}) command does not execute right after getting a response from the web?

I am getting all the lats and logs of appropriate locations. But can't store it into an array.

I removed the key for the purpose of security. How can I store the object into an array?

 var coordinates = [];
    for(var i = 0; i < locations.length; i++) {
        console.log(locations[i]);
        geocode(locations[i]);
    }


    function geocode(location) {
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params : {
                address: location,
                key : 'api_key'
            }
        })
            .then(function(response){
               var lat = response.data.results[0].geometry.location.lat;
               var lng = response.data.results[0].geometry.location.lng;
               coordinates.push({"lat" : lat, "lng": lng});
               
            })
            .catch(function(error) {
                console.log(error);
            });
    }
  • You are with `coordinates` issue is you are probably reading it before the asynchronous calls are done. – epascarello Aug 31 '20 at 16:19
  • https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello Aug 31 '20 at 16:20
  • as @epascarello mentions, the time at which you attempt to check the array is very important. It seems likely that you are trying to check it before the async calls have finished. I would recommend you include more code to show where you are checking the array. – adammtlx Aug 31 '20 at 17:59

2 Answers2

1

axios.get is not blocking, meaning that the request will be started, then code will continue to run, then the request finishes and it'll run the code inside the .then. You should return the promise from the geocode function then use an async function to await the result.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • thanks. I understood your point. I solved the issue with the help of @Mitya 's code. –  Aug 31 '20 at 16:33
0

However, at the end, when I check the coordinates array, it is shown as an empty array.

At the end of what? Probably the for loop, in which case, you're reading it too early. Keep in mind that the objects are pushed to coordinates asynchronously, i.e. after your for loop completes.

There's a few ways round this. One would be to log the promises returned by Axios.get() and then do a Promise.all() to log the array, once all promises have been resolved.

let coordinates = [],
    promises = [];
for(let i = 0; i < locations.length; i++) {
    console.log(locations[i]);
    promises.push(geocode(locations[i]));
}
Promise.all(promises).then(() => {
    console.log(coordinates); //will now be populated
});

Finally, change

axios.get('...

to

return axios.get('...
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • It gives the coordinates. But I can't use the `coordinates` array outside of this scope. `Promise.all(promises).then(() => { console.log(coordinates); //will now be populated });` Outside of this scope, `coordinates` array gives me nothing again as empty array. –  Aug 31 '20 at 16:52