Parallel Requests (fetching data from multiple sources)

Heewon👩🏻‍💻·2024년 5월 15일
0

Recap: 페이지이동시 데이터 전달하기

//1. 전달되어야할 api주소를 export처리해준다.

export const APIURL = "https://nomad-movies.nomadcoders.workers.dev/movies";

2.받아와야 하는 페이지에서 import 해주고 async function을 만들어준다.

import { APIURL } from "../../../(home)/page";
async function getMovie(id) {
  const response = await fetch(`${APIURL}/${id}`);
  return response.json();
}
export default async function MovieDetail({ params: { id } }) {
  const movie = await getMovie(id);
  return <h1>Movie {movie.title}</h1>;
}

await를 통해 데이터를 가져온다.

Parallel Requests (fetching data from multiple sources)

아래와 같은 코드가 있고 문제점을 생각해보면...

import { APIURL } from "../../../(home)/page";

async function getMovie(id) {
  console.log(`fetcing movies: ${Date.now}`);
  await new Promise((resolve) => setTimeout(resolve, 5000));
  const response = await fetch(`${APIURL}/${id}`);
  return response.json();
}

async function getVideos(id) {
  console.log(`fetcing videos: ${Date.now}`);
  await new Promise((resolve) => setTimeout(resolve, 5000));
  const response = await fetch(`${APIURL}/${id}/videos`);
  return response.json();
}

export default async function MovieDetail({ params: { id } }) {
  console.log("=================");
  console.log("start fetching!");
  const movie = await getMovie(id);
  const video = await getVideos(id);
  console.log("end fetching");
  return <h1>Movie {movie.title}</h1>;
}

프로그래밍 언어는 위에서 아래로 읽혀 내려가며(먼저 정의된 함수 실행 후 다음 기능이 실행된다.)
이런경우 앞에 정의된 기능의 로딩이 느려지면, 다음에 오는 코드가 데이터를 가져오는데 적은 시간을 필요로 한다고 해도 무조건 적으로 앞 기능의 기능이 끝마칠때까지 기다려야한다는 문제점이 발생한다.
console.log를 통해 로드된 시간을 확인해 보면 아래와 같다.

순차적으로 출력되는 문제점을 해결하기위해 Promise.all([])을 사용한다.

import { APIURL } from "../../../(home)/page";
async function getMovie(id) {
  console.log(`fetcing movies: ${Date.now}`);
  await new Promise((resolve) => setTimeout(resolve, 5000));
  const response = await fetch(`${APIURL}/${id}`);
  return response.json();
}

async function getVideos(id) {
  console.log(`fetcing videos: ${Date.now}`);
  await new Promise((resolve) => setTimeout(resolve, 5000));
  const response = await fetch(`${APIURL}/${id}/videos`);
  return response.json();
}

export default async function MovieDetail({ params: { id } }) {
  console.log("=================");
  console.log("start fetching!");
  const [movie, video] = await Promise.all([getMovie(id), getVideos(id)]);
  return <h1>Movie {movie.title}</h1>;
}

Promise.all([])의 배열요소로 기능들을 넣어준 뒤 await해주는 방식이다.
getMoive와 getVideos기능을 실행시킨뒤 결과값을 배열로 반환시켜준다.
동시에실행된다. Promise.all을 사용하기전엔 합 10초가 걸렸다면 동시에 작업했을경우 5초가 소요된다. 이를 데이터를 병렬적(Parallel)으로 fetching하는 방법이다.

profile
Interested in coding, meat lover, in love with dogs , enjoying everything happens in my life.

0개의 댓글