본문 바로가기

코딩도 합니다/JS

[자바스크립트 js] rejected 상태일 때 콜백 추가 / catch 메소드 / finally 메소드



  promise 객체가 rejected 상태일 때 콜백 추가하기

promise객체가 rejected 상태됐을 때 실행할 콜백을 설정하고 싶다면,

then메소드의 2번째 파라미터로 원하는 콜백을 넣어주면 된다.

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


     : fullfilled 상태가 되면 실행 => 작업 성공 결과
     : rejected 상태가 되면 실행 => 작업 실패 정보

 

 

 

 

  catch 메소드

  • promise객체가 rejected 상태가 되면 실행할 콜백을 등록하는 메소드.
  • then메소드에 2번째 콜백을 넣는 방법 말고 catch메소드를 사용할 수도 있다.
  • catch메소드는 then메소드를 약간 변형시킨 것과 같다.
    .then(undefined, (error) => { console.log(error); }) 와 아래 코드의 catch문은 같은 내용이기 때문이다.
    catch메소드는 첫번째 파라미터에 undefined를 넣은 then메소드와 같다는 걸 이해하고 있으면 된다.
fetch('https://tooktak.com/doit')
   .then((response) => response.text())
   .catch((error) => { console.log(error); })
   .then((result) => { console.log(result); });

 

잠깐만✋🏼 실무에서 catch 메소드 어떻게 써야 할까?

  • 대게 promise chain의 마지막에 하나만 쓴다.
  • 중간에 에러가 발생해도 catch 메소드가 그 대안을 뒤로 넘겨 줄 수있음녀 catch 메소드를 중간에 쓰거나, 여러개 사용해도 괜찮다.
  • promise chain 중에서 에러가 발생해도, 실패한 작업 대신 다른 방법을 통해서 작업을 정삭적으로 끝마칠 수 있는 상황이라면 catch 메소드를 중간에 사용할 수도 있다.
fetch('https://tooktak.com/doit');
   .then((response) => response.text())
   .then((result) => {
      console.log(result);
      throw new Error('에러에러');
   });
   .catch((eroor) => { console.log(error); })
});

 

 

 

 

  finally 메소드

  • promise 객체가 fullfied 상태가 되든, rejected가 되든 상관 없이 항상 무조건 실행하고 싶은 콜백이 있을 경우 사용한다.
  • promise chain에서 catch 메소드 보다 더 뒤에 쓴다. (보통 catch 메소드 바로 뒤에 쓴다.)
  • 작업 성공 결과나 작업 실패 결과가 필요하지 않기 때문에 파라미터가 따로 필요 없다.
fetch('https://tooktak.com/doit');
   .then((response) => response.text())
   .then((result) => {
      console.log(result);
      throw new Error('에러에러');
   });
   .catch((eroor) => { console.log(error); })
   .finally(() => { console.log('끝'); });
});

 

728x90