-2

when this code is written

var holder = [];
const compile = () =>{
    let latitude = 0;
    let longitude = 0;
    for (let i = 0; i < holder.length; i++) {

        Geocode.fromAddress(holder[i].city).then(
            (response) => {
              const { lat, lng } = response.results[0].geometry.location;

                const foo = {lat, lng}

                longitude += Number(foo.lng);
                console.log(longitude)
                latitude += Number(foo.lat);
                console.log(latitude)

            },
            (error) => {
              console.error(error);
            }
          );
      } 
      console.log("lat: " + latitude)
    latitude = latitude/holder.length;
    longitude = longitude/holder.length;

    console.log("lattitude: ", latitude, " longitude: ", longitude);
}

the output looks like this

lat: 0 AddBox.js:49
lattitude:  0  longitude:  0 AddBox.js:53
-118.2436849 AddBox.js:39
34.0522342 AddBox.js:41
-192.7821738 AddBox.js:39
74.62067049999999

why would the console.log be printing before the for loops runs?

I'm trying to average out the longitudes and latitudes of several locations using geocode, but the code doesn't seem to be running from top to bottom

Skiddzie
  • 1
  • 1
  • The `.then()` callback to `.fromAddress()` runs when the asynchronous request completes. The `for` loop does not (and cannot) wait for that. – Pointy Mar 09 '23 at 23:06
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Christian Vincenzo Traina Mar 09 '23 at 23:08

1 Answers1

0

You can use async/await to handle asynchronous operations more conveniently.

const compile = async () => {
    let latitude = 0;
    let longitude = 0;
    for (let i = 0; i < holder.length; i++) {
        const response = await Geocode.fromAddress(holder[i].city);
        const { lat, lng } = response.results[0].geometry.location;
        const foo = {lat, lng}
        longitude += Number(foo.lng);
        console.log(longitude)
        latitude += Number(foo.lat);
        console.log(latitude)
    } 
    console.log("lat: " + latitude)
    latitude = latitude/holder.length;
    longitude = longitude/holder.length;
    console.log("lattitude: ", latitude, " longitude: ", longitude);
};
// note: the compile function now should be awaited
Unmitigated
  • 76,500
  • 11
  • 62
  • 80