简体   繁体   中英

How to store the object in array right after fetching it from API in Javascript?

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);
            });
    }

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.

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 , ie 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('...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM