Smilyface Smilyface - 4 months ago 7
Node.js Question

Node js promise in a method

I am new to asynch programming and I cannot understand Promises. I am trying to use a reverse geocoding library where lat/long is sent to Google Maps and a json detailing the location is returned.

class Geolocator
{
constructor()
{
let options = {
provider: 'google',
httpAdapter: 'https',
apiKey: mapsKey,
formatter: null
};

this._geocoder = NodeGeocoder(options);
}

getLocationId(lat, lon)
{
this._geocoder.reverse({lat: lat, lon: lon})
.then(function(res) {
return this._parse(null, res);
})
.catch(function(err) {
return this._parse(err, null);
});
}

_parse(err, res)
{
if (err || !res)
throw new Error(err);
return res;
}


When I call
geolocator.getLocationId
I get
undefined
. I am guessing that the method call exits and returns
undefined
. What is the best way to encapsulate the promise?

Answer

As @smarx said, you would return the Promise at getLocationId() and execute then branch:

class Geolocator {
  // ...

  /* returns a promise with 1 argument */
  getLocationId(lat, lon) {
   return this._geocoder.reverse({ lat, lon })
  }
}


// calling from outside
geolocator
  .getLocationId(lat, lon)
  .then((res) => {
     // whatever
  })
  -catch((err) => {
    // error
  })