2017-02-28 2 views
0

이 코드를 고려하십시오. first catch 블록이 실행되면, 문제가 testP 또는 first then 약속에 의해 발생했는지 여부를 판단 할 수있는 문제가 있다고 가정합니다.약속 코드의 충돌

var testP = function(){ 
    return new Promise(function(resolve, reject){ 
     //reject or resolve 
    }); 
} 

testP().then(function(res){ 
    console.log("first then"); 
    console.log(res); 
    return new Promise(function(resolve,reject){ 
     // reject or resolve 
    }) 
}) 
.catch(function(err){ 
    console.log("first catch"); 
    console.log(err); 
}) 

답변

0

수 없습니다.

구별하려면? 두 번째 인수 인 then을 사용해야합니다.

testP().then(function(res){ 
    console.log("first then"); 
    console.log(res); 
    return new Promise(function(resolve,reject){ 
     // reject or resolve 
    }) 
}, function(err){ 
    console.log("first catch"); 
    console.log(err); 
}) 
.catch(function(err){ 
    console.log("second catch"); 
    console.log(err); 
}) 
+0

OP의 '오류'유형을 확인할 수 없습니까? – niceman

+0

@niceman 예, 그렇습니다. 약속이 특정 오류 (예 : 'reject (새로운 Error ("TESTP_ERROR"))'와'reject (새로운 Error ("THEN_ERROR"))'를 호출하면 캐치 콜백에서'err.message'를 검사하여 그에 따라 행동 할 수 있습니다. 만약에 당신이'Error'를 확장하는 자신의 에러를 정의하는 경로를 원한다면'if (err instanceof MyCustomError')를 체크 할 수 있습니다. 일반적으로 다른 런타임 에러가 코드에서 발생할 수도 있습니다. 예를 들어 함수 호출 정의되지 않은 객체에 대해서는'catch' 콜백을 호출한다는 점도 고려해야합니다. –

+0

일반적으로이 문제를 해결하는 방법은 사용자가 잡는 오류의 유형을 구분하는 것입니다. 특정 오류를 처리 한 다음 거기에서 체인을 계속하게하려면 잡아두고 자하는 오류 인 .then() 바로 뒤에'.catch()'를 넣는다. – jfriend00