2016-08-01 2 views
0

약속의 then 함수에서 발생하는 오류를 어떻게 처리합니까?다음 함수에서 오류를 약속합니다

예를 들어
getLocationId(lat, lon, callback) 
{ 
    let self = this; 

    return this._geocoder.reverse({lat: lat, lon: lon}) 
     .then(this._parse) 
     .catch(function(err) { 
      callback(err); 
     }); 
} 

_parse(res) 
{ 
    if (res.length < 1) 
     throw new Error('No results from Maps API'); 

    let value = res[0].administrativeLevels; 

    if (!value || value.length < 1) { 
     throw new Error('No administrative levels available'); 
    } 

    if ('level2long' in value) 
     return value.level2long; 
    if ('level1long' in value) 
     return value.level1long; 

    throw new Error('No suitable location found'); 
} 

, 어떻게 오류를 던지고 this._parse 처리합니까? 나는 catch 함수가 reject 핸들러만을 다룬다고 생각했다. then에 발생한 오류도 처리합니까?

+1

O.T. : 여기

은 예입니다 그러나 관련 :'callback'을 전달할 필요는 없습니다. getLocationId (lat, lon, errorHandler) 대신에,'getLocationId (lat, lon) .catch (errorHandler)'와 완전히 같은 효과를 얻을 수 있습니다. –

답변

0

.then() 처리기에서 발생 된 예외는 약속 인프라에서 자동으로 포착되어 현재 약속 체인을 거부 된 약속으로 전환합니다. 체인은 다음 .catch() 처리기로 건너 뜁니다. 여기서 예외는 오류 거부 이유가됩니다.

Promise.resolve().then(function() { 
    throw "foo"; 
}).then(function() { 
    console.log("in 2nd .then() handler");  // will not get here 
}).catch(function(err) { 
    console.log(err);       // will show "foo" 
}); 
관련 문제