의문점 해결하기
Promise를 사용할 때 .catch로 에러를 처리하는 것이 .then의 두 번째 인자로 에러를 처리하는 것보다 더 효율적인 이유
1two13
2023. 2. 7. 15:44
728x90
반응형
의문점이 생긴 이유
Promise가 에러를 처리하는 방법은 2가지가 있다.
1. .then()의 두 번째 인자로 에러를 처리하는 방법
2. .catch()를 이용하는 방법
둘 중에 어떤 방법이 더 효율적일까? 라는 궁금점이 생겨 작성해보았다.
728x90
예제 코드와 콘솔창 확인
1. .then()의 두 번째 인자로 에러를 처리하는 경우**
function getData() {
return new Promise(function(resolve, reject) {
resolve('hi');
});
}
getData().then(function(result) {
console.log(result);
throw new Error("Error in then()"); // Uncaught (in promise) Error: Error in then()
}, function(err) {
console.log('then error : ', err);
});

2. .catch()로 에러를 처리하는 경우
function getData() {
return new Promise(function(resolve, reject) {
resolve('hi');
});
}
getData().then(function(result) {
console.log(result); // hi
throw new Error("Error in then()");
}).catch(function(err) {
console.log('then error : ', err); // then error : Error: Error in then()
});

반응형
결론
결론적으로 가급적 .catch()로 에러를 처리하는 게 더 효율적이다. 위의 코드에서 볼 수 있듯이 .then()의 두 번째 인자로 에러를 처리하게 되면 첫 번째 콜백 함수 내부에서 오류가 나는 경우 두 번째 콜백 함수를 검사하지 않기 때문에 오류를 제대로 잡아내지 못하기 때문이다.
참고자료
728x90
반응형