Smilyface Smilyface - 1 year ago 71
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
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
I get
. I am guessing that the method call exits and returns
. What is the best way to encapsulate the promise?

Answer Source

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
  .getLocationId(lat, lon)
  .then((res) => {
     // whatever
  -catch((err) => {
    // error
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download