본문 바로가기
JavaScript

[TIL] JavaScript fetch와 async await 사용법

by 어느새벽 2024. 6. 28.

1. fetch 사용법

  1. fetch : 데이터 요청을 위한 함수
  2. then : fetch가 완료되면 그때 ~라는 뜻
  3. json() : 자바스크립트 데이터로 변경하는  함수

 

fetch 함수를 쓰기 위해 필요한 정보 (예시 데이터 : https://developer.themoviedb.org/reference/movie-top-rated-list )

  1. API주소를 알아야함 ex) https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1
  2. 메소드를 알아야 함 ex) get, post 등등

 

아래 예시 코드를 보며 좀 더 이해해보자! 

const options = {
 method: 'GET', 
 headers: {
	accept: 'application/json'
 }
};

fetch('https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1', options)
  .then(fetch의 응답결과 => fetch의 응답결과.json())
  .then(json까지 완료한 결과 => console.log(json까지 완료한 결과))
  .catch(err => console.error(err));

 

예시 코드1

fetch("https://comic.naver.com/api/home/component?type=GENRE_RANK&genre=DRAMA") 
	.then((res) => res.json())
	.then((data) => console.log(data))
  1. fetch 괄호 안에 주소 작성
  2. 메소드 작성 (GET메소드는 생략해도 됨)
  3. 첫번째 then : 네트워크 요청 데이터 (json) => 자바스크립트에서 사용할 수 있는 객체로 변경
  4. 두번째 then : 사용할 수 있는 data => 화면에 보여주거나 조작할 수 있음

 

예시 코드 2

fetch("<웹툰 추가하는 주소>", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    id: 123,
    title: "내가 만든 웹툰",
    content: "웹툰 정보~~~",
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));
  1. fetch 괄호 안에 주소 작성
  2. fetch 메소드의 두번째 파라미터에 객체 넣기
  3. 객체 안에 method: "POST" 넣기
  4. headers => 추가 정보
  5. body => 데이터 전달 시 자바스크립트 데이터를 json으로 변경
  6. 첫번째 then : 네트워크 요청 데이터 (json) => 자바스크립트에서 사용할 수 있는 객체로 변경
  7. 두번째 then : 사용할 수 있는 data => 화면에 보여주거나 조작할 수 있음

 

*headers? body?

- 데이터를 요청할때 쓰이는 카테고리라고 생각하면 된다. headers로 타입을 알려주고 그에 해당하는 body안의 데이터 내용을 보내주는 것으로 개발자들끼리 약속한 사용구조이다. headers에는 매우 다양한 설정 타입이 있다.

 

2. async await 사용법 

  1. 비동기 함수 만들기 ( async ~~ )
  2. .then 지우고 await로 바꾸기
  3. 변수에 담기

 

예시로 비교하기

 

// 변경 전 코드

const id = new URLSearchParams(location.search).get("id");

const postContainer = document.querySelector(".post-container");

fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
  .then((response) => response.json())
  .then((data) => {
    postContainer.innerHTML = `
        <div class="card">
          <div class="extra-info">
            <div>사용자ID: ${data.userId}</div>
            <div>게시물 번호: ${data.id}</div>
          </div>
          <h3 class="title">제목</h3>
          <div>${data.title}</div>
          <h3 class="content">내용</h3>
          <p>${data.body}</p>
        </div>
      `;
  });


// 리팩토링 후 코드

const id = new URLSearchParams(location.search).get("id");

const postContainer = document.querySelector(".post-container");

const getPost = async () => {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
  const data = await res.json();
  return data;
};

const render = async () => {
  const data = await getPost();
  postContainer.innerHTML = `
        <div class="card">
          <div class="extra-info">
            <div>사용자ID: ${data.userId}</div>
            <div>게시물 번호: ${data.id}</div>
          </div>
          <h3 class="title">제목</h3>
          <div>${data.title}</div>
          <h3 class="content">내용</h3>
          <p>${data.body}</p>
        </div>
      `;
};

render();

 

try catch 알아보기

fetch("https://jsonplaceholder.typicode.com/posts")
  .then((response) => response.json())
  .then((data) => {
	   // 생략
  })
	.catch((error) => {
		console.log("에러났어요!", error.message)
	})

 

에러가 발생하면 실행시킬 코드를 .catch() 안에 작성한다.

  • 에러 나서 흰 화면이 뜨지 않게 방지
  • 메신저에 알람을 보낼 수도 있음
  • 다른 화면으로 전환하는 등 실행 가능

 

try catch도 async await로 작성하기

const makePostsHTML = async () => {
	try {
	  const data = await getPosts();
	} catch (e) {
		console.log("에러났어요!", e.message)
	}

  // 코드 생략
};