2016-07-31 82 views
0

我是新來的異步編程,我無法理解承諾。我正在嘗試使用反向地理編碼庫,其中lat/long發送到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; 
    } 

當我打電話geolocator.getLocationId我得到undefined。我猜測該方法調用退出並返回undefined。封裝承諾的最佳方式是什麼?

+0

'getLocationId'返回undefined。如果你想返回你正在進行的調用的結果,在它前面放一個「return」。 – smarx

+0

@smarx我試過了,它返回一個Promise對象。不是迴應。 – mrQWERTY

+0

那麼它不能返回響應......響應還不存在。你需要在Promise上調用'.then',並傳入一個函數來調用響應。 – smarx

回答

1

像@smarx說,你將在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 
    })