mrQWERTY
mrQWERTY

Reputation: 4149

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?

Upvotes: 0

Views: 58

Answers (1)

Manu Artero
Manu Artero

Reputation: 10253

Like @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
  })

Upvotes: 1

Related Questions