2016-07-31 10 views
0

私は非同期プログラミングの新人です、私は約束を理解できません。私は緯度/経度がGoogle Mapsに送信され、場所を詳述しているjsonが返される逆ジオコーディングライブラリを使用しようとしています。ノードjsメソッドで約束

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; 
    } 

私はundefinedを得るgeolocator.getLocationIdを呼び出します。私は、メソッド呼び出しが終了し、undefinedを返すと推測しています。約束をカプセル化する最良の方法は何ですか? @smarxが言ったように

+0

'getLocationId'はundefinedを返しますが。あなたが行っている呼び出しの結果を返す場合は、その前に 'return'を置きます。 – smarx

+0

@smarx私はそれを試みました、それはPromiseオブジェクトを返します。レスポンスではありません。 – mrQWERTY

+0

これは応答を返すことができません...応答はまだ存在しません。プロミスで '.then'を呼び出し、レスポンスで呼び出される関数を渡す必要があります。 – smarx

答えて

1

、あなたはgetLocationId()Promiseを返し、thenブランチを実行します:あなたが何かを返していないので、

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