Front-end/JavaScript

JS) Promise를 반환하는 함수의 다양한 표현 (fetch, axios)

오열매 2023. 3. 1. 15:20

이번 예시는 React Query v4 의 useQuery라는 훅의 Option인 queryFn을 예시로 살펴본다.

 

queyrFn는 promise를 반환하는 함수여야 한다. useQuery는 주로 데이터 fetching으로 사용하는데, 이를 위해 fetch 와 axios를 이용한 다양한 표현들을 알아보자.

 

각 api는 async/await 와 Promise chaining 을 사용하여 나타낼 수 있다.

 

참고로, axios와 fetch의 성능 차이는 크게 없으며, 아래 함수들의 return값은 모두 Promise{<pending>} 이다.

 


axios와 fetch의 성능 차이는 크게 없다.

 

다만, axios가 가독성이 더 좋고 사용할 수 있는 기능이 많기 때문에 더 선호되는 경향이 있다.

 

fetch는 웹 내장 함수이기 때문에 설치 없이 사용할 수 있다.

 


1) Axios + Promise chaining     

 

export const coinsFetcher = () =>
  axios.get("URL").then((res) => res.data);

 




2) Fetch + Promise chaining

 

export const coinsFetcher = () =>
  fetch(`${BASE_URL}/coins`).then((res) => res.json());

 

 

# Promise chaining으로 작성하면 좀 더 간결한 코드를 작성할 수 있다.




3)  Axios + async/await

 

export const coinsFetcher = async () => {
  const { data } = await axios.get("URL");
  return data;
};

 




4) Fetch + async/await

 

export const coinsFetcher = async () => {
  const response = await fetch("URL");
  const data = await response.json();

  return data;
};

 

 

# async/await 으로 작성하면 가독성이 더 좋아진다.




5) Fetch + async/await + IIFE 

export const coinsFetcher = async () => {
  return (async () =>await (await fetch("URL")).json())();)
};

 

 

# IIFE는 코드가 간결해지지만, 가독성이 안 좋아지는 단점이 있다.

 

 


참고)

 

- https://tanstack.com/query/v4/docs/react/reference/useQuery

- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions