Fetch, Then, Promise에 대하여

채무·2024년 1월 31일

Web

목록 보기
7/11

fetch() 함수

fetch는 비동기 방식으로 서버에 request를 보내고, 서버로부터 response를 받는 함수이다


then() 메소드

then 메소드는 response가 왔을 때 등록된 콜백 함수를 실행한다


ex) fetch와 then을 사용하여 response 값을 출력하는 코드이다

fetch('https://www.google.com')
  .then((response) => response.text())
  .then((result) => { console.log(result); });

Promise 객체

Promise 객체는 fetch 함수와 then 메소드가 리턴하는 객체이다

Promise 객체의 등장 이유

  • fetch() 함수 내부에 바로 콜백을 넣는 방식으로 코드를 작성하면 콜백 지옥에 빠질 수 있다
  • Promise Chaining을 통해 콜백 지옥 현상을 피하고, 깔끔한 코드로 비동기 작업들을 처리할 수 있다
  • 또한 Promise 객체를 통해 pending, fulfilled, rejected 상태와 then, catch, finally 메소드 등을 사용하여 정교한 설계를 할 수 있다

콜백 지옥(callback hell)이란?

fetch('https://first.com', (response) => {
  // Do Something
  fetch('https://second.com', (response) => {
    // Do Something
    fetch('https;//third.com', (response) => {
      // Do Something
      fetch('https;//fourth.com', (response) => {
        // Do Something
      });
    });
  });
});
  • fetch 함수의 콜백에 fetch 함수가 있고, 그 함수의 콜백 안에 fetch가 들어가는 코드가 반복되면 가독성이 떨어지는 문제가 발생한다
  • 이러한 현상을 '콜백 지옥'이라고 한다
profile
개발한 기발자

0개의 댓글