Cute Running Puppy

🟡JS, React

# fetch 비동기 통신

뭉지맘 2025. 3. 21. 10:09

fetch

fetch API를 사용하여 데이터를 비동기적으로 가져오는 코드

AJAX와 같은 역할을 하지만, XMLHttpRequest 객체를 사용하는 기존의 AJAX 방식보다 더 간단하고 직관적인 방식

 

AJAX와 유사한 방식으로 데이터를 가져오지만, fetch는 최신 API로, Promise 기반으로 작동한다.

# Promise는 비동기 작업을 반환값 으로 처리

 

fetch와 기존 AJAX 차이점

 

1. AJAX (XMLHttpRequest 사용):

  • 비동기적으로 데이터를 요청하고 받아옴.
  • 콜백 방식(비동기 처리가 콜백 함수로 이루어짐).
// 콜백 방식으로 처리
fetchData(function(err, data1) {
  if (err) return console.error(err);
  processData(data1, function(err, data2) {
    if (err) return console.error(err);
    saveData(data2, function(err, result) {
      if (err) return console.error(err);
      console.log(result);
    });
  });
});

2. fetch API:

  • Promise 기반으로, 더 깔끔하고 직관적인 코드 작성이 가능.
  • then()과 catch()로 비동기 처리가 이루어짐.
// Promise 방식으로 처리
fetchData()
  .then((data1) => {
    return processData(data1);
  })
  .then((data2) => {
    return saveData(data2);
  })
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error("에러 발생:", error);
  });

 

 

예시)

// 클라이언트에서 fetch로 데이터 요청
document.addEventListener('DOMContentLoaded', function () {
    fetch('/getUserData')  // 서버에서 데이터 요청
        .then(response => response.json())  // 응답을 JSON으로 파싱
        .then(data => {
            console.log('Fetched User Data:', data.userData);
            // 데이터를 화면에 표시하거나 다른 처리를 할 수 있음
        })
        .catch(error => {
            console.error('Fetch Error:', error);
        });
});