2016-07-31 64 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 
    })