.then.catch / try catch 차이

KHW·2022년 6월 22일
3

Javascript 지식쌓기

목록 보기
95/95

.then.catch / try catch 차이

사실 차이라곤 딱히 없는 것 같다.
단지 try catch는 try와 catch안에서 Promise로 출력되는 것을 막기 위해 async await으로 처리해야한다.

220702

아니 차이가 있다.
then catch는 Promise에 대한 에러처리 및 진행을 다루기 위한 것이고
try catch는 Promise가 아닌 것에 대한 에러처리 및 진행을 다루기 위한 것이다.

  • 즉, try catch는 async함수 안에서 동작하는 Promise가 아닌 내부코드에 대해서의 try catch로 처리하는 이유이다.

node.js에서 성공 예시로 보기

.then.catch

// .then.catch
fs.readFile("./text.txt")
  .then((data) => console.log(data))
  .catch(console.error);

try catch

// try catch
const tried = async () => {
  try {
    const data = await fs.readFile("./text.txt");
    console.log(data);
  } catch (err) {
    console.log(err);
  }
};

tried();

둘다 정상적으로 data가 출력된다.

node.js에서 실패 예시로 보기

.then.catch

// .then.catch
fs.readFile("./tex.txt")
  .then((data) => console.log(data))
  .catch(console.error);

try catch

// try catch
const tried = async () => {
  try {
    const data = await fs.readFile("./tex.txt");
    console.log(data);
  } catch (err) {
    console.log(err);
  }
};

tried();

둘다 존재하지않은 tex.txt 를 readFile 하려하니 오류가 발생한 부분을 각각 .catchcatch(err) 로 처리하여 같은 출력을 시킨다.

정리하기

try catch든 .then.catch든 같은 결과를 만들수 있다.
그러기 위해서는 try catch는 async await를 쓰지않으면 Promise 형태로 출력이 되기때문에 async await로 잘 묶어 사용한다.

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글