0

I have been trying to create some seed files, while also using the google api, to create some longitude and latitudes for each city. The whole process and code works, but I believe there is an issue with the asynchronous call as I cannot properly save the coordinates. Here is a snippet from my code:

var coordinates = getCoordinates("syndey", "australia");
console.log("these are the coordinates " + coordinates);

function getCoordinates(city, country) {
  var coordinates = {
    lat: Number,
    lng: Number
  };

  const url = "https://maps.googleapis.com/maps/api/geocode/json?components=locality:"+city+"|country:"+country +"&key=MYAPIKEY";
  request(url, (err, resp, body)=> {
     body = JSON.parse(body);
     console.log("this is the body: " + JSON.stringify(body.results[0].geometry.location.lat));
     if (err) {
       res.status(401).json({message: "error"});
      } else {
        coordinates.lat = body.results[0].geometry.location.lat;
        coordinates.lng = body.results[0].geometry.location.lng;
      }
      console.log("before exit: " + JSON.stringify(coordinates));
        return coordinates;
      });
}

When the code executes, i get the following consoles in my terminal:

these are the coordinates undefined

this is the body: -33.8688197

before exit: {"lat":-33.8688197,"lng":151.2092955}

As you can see, the coordinates are Undefined, and its clearly because the before exit console log is executed after.

I did try a callback but it did not work.

Any ideas?

Thanks Andreas

  • You cannot return an asynchronously retrieved value from your `getCoordinates()` function. That function returns long before the asynchronous callback has been called so there is no value to return. Your current `return` statement is inside the callback which is NOT a return statement from your `getCoordinates()` function. You need to either return a promise that is hooked up to the result or you need to pass in a callback which you will call when the result is available. See the question yours has been marked a dup of for a lot more detail on your options. – jfriend00 May 28 '17 at 15:13
  • In addition, your error handling is messsed up as you do two completely different things when there's an error vs. no error which are not really compatible for the caller. The function should consistently either send the response or pass back the result (including passing back an error if there is one), not doing the opposite when there's an error. – jfriend00 May 28 '17 at 15:15

0 Answers0