then&catch

thdy3k·2023년 12월 5일
0

.then() 및 .catch()은 JavaScript 프로미스 (Promise
:비동기를 간편하게 처리할 수 있도록 도와주는 자바스크립트안에 내장되어 있는 객체이다.)를 사용할 때의 메서드입니다.

.then():

프로미스가 성공적으로 처리되었을 때 실행되는 메서드입니다.
.then()은 콜백 함수를 인자로 받습니다. 이 콜백 함수는 프로미스가 성공적으로 완료되면 실행됩니다.
프로미스가 비동기 작업을 수행하고 나서 성공적으로 완료되었을 때 어떤 작업을 수행하고자 할 때 사용됩니다.

somePromiseFunction()
  .then((result) => {
    console.log('Promise resolved with result:', result);
  })
  .catch((error) => {
    console.error('An error occurred:', error);
  });

.catch():

프로미스에서 발생한 에러를 처리하기 위한 메서드입니다.
.catch()는 실패한 프로미스의 에러를 처리하기 위한 콜백 함수를 인자로 받습니다. 이 콜백 함수는 프로미스가 실패할 때 호출됩니다.
.then() 체인 중 어떤 .then()에서라도 에러가 발생하면 .catch()가 호출됩니다.

somePromiseFunction()
  .then((result) => {
    console.log('Promise resolved with result:', result);
  })
  .catch((error) => {
    console.error('An error occurred:', error);
  });

프로미스는 비동기 작업의 완료 또는 실패를 나타내는 객체로, .then()과 .catch()는 이를 활용하여 비동기 코드를 보다 효과적으로 다룰 수 있도록 도와줍니다.

0개의 댓글