본문 바로가기

JavaScript/Web Development

[JavaScript] catch 메소드

rejected 상태가 되면 실행할 콜백을 설정하는 방법으로는 다음과 같은 방법이 있음.

 

1. then 메소드의 두번째 콜백함수를 설정

 

fetch('https://jsonplaceholder.typicode.com/users')
    .then((response) => response.text(), (error) => { console.log(error); })
    .then((result) => { console.log(result); });

 

2. catch 메소드 활용 : promise 객체가 rejected 상태가 되면 실행할 콜백을 등록하는 메소드

 

fetch('https://jsonplaceholder.typicode.com/users')
    .then((response) => response.text())
    .catch((error) => { console.log(error); })
    .then((result) => { console.log(result); });

위의 첫번째 then 메소드 안에 있던 두번째 콜백을 catch 메소드의 콜백으로 넣음.

 

존재하지 않는 url 주소입력

 

 

catch 메소드는 then 메소드를 약간 변환시킨 형태인데, 

 

위처럼 두 코드는 똑같음.

catch 메소드는 첫번째 파라미터에 undefined 를 넣고 두번째 콜백을 넣은 then 메소드와 동일함.