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
。封裝承諾的最佳方式是什麼?
'getLocationId'返回undefined。如果你想返回你正在進行的調用的結果,在它前面放一個「return」。 – smarx
@smarx我試過了,它返回一個Promise對象。不是迴應。 – mrQWERTY
那麼它不能返回響應......響應還不存在。你需要在Promise上調用'.then',並傳入一個函數來調用響應。 – smarx