https://sjwoo1999.github.io/FC-NBC-MOVIE-SEARCH/
내배캠 최고 평점 영화 콜렉션
sjwoo1999.github.io
fetch 함수의 비동기적 특성
fetch 함수는 비동기적으로 작동하는 함수입니다.
즉, fetch 요청을 시작하면 즉시 다음 코드가 실행되며,
서버로부터 응답이 도착할 때까지 기다리지 않습니다.
fetch 함수의 비동기적 특성을 이해하기 위해서는 먼저 비동기식 처리에 대한 이해가 필요합니다.
비동기식 처리란, 한 작업이 완료되기를 기다리지 않고 다음 작업을 실행하는 처리 방식을 말합니다.
자바스크립트는 기본적으로 동기식 처리 방식을 사용합니다.
즉, 한 작업이 완료되기 전까지 다음 작업을 실행하지 않습니다.
따라서, fetch 함수를 사용하면 다음과 같은 문제가 발생할 수 있습니다.
fetch 요청이 완료되기 전에 다음 코드가 실행되어 오류가 발생할 수 있습니다.
fetch 요청이 완료되는 시점을 알 수 없어서 응답을 처리하는 데 어려움이 있을 수 있습니다.
fetch 함수의 비동기적 특성의 해결 방법
fetch 함수의 비동기적 특성을 해결하기 위해서는 다음과 같은 방법을 사용할 수 있습니다.
then 메서드 사용: then 메서드를 사용하여 fetch 요청의 응답이 성공적으로 도착했을 때
실행할 코드를 지정할 수 있습니다.
Promise 사용: Promise를 사용하여 fetch 요청의 응답을 처리할 수 있습니다.
then 메서드 사용
then 메서드는 fetch 요청의 응답이 성공적으로 도착했을 때 실행할 코드를 지정하는 메서드입니다.
then 메서드의 첫 번째 인자로 응답 객체가 전달되고,
두 번째 인자로 응답 객체를 처리할 코드가 지정됩니다.
const url
= "https://api.themoviedb.org/3/movie/550?api_key=d1015a8059e64d21776b4be2ac2efc2d";
fetch(url)
.then((response) => {
// 응답 객체를 처리하는 코드
});
이 코드의 경우, fetch 요청이 성공적으로 도착하면 응답 객체가 response 변수에 저장됩니다.
그리고 response 변수를 사용하여 응답을 처리하는 코드가 실행됩니다.
Promise 사용
Promise는 비동기 작업의 결과를 나타내는 객체입니다. Promise는 상태가 세 가지로 나뉩니다.
pending: 작업이 아직 완료되지 않은 상태
fulfilled: 작업이 성공적으로 완료된 상태
rejected: 작업이 실패한 상태
Promise를 사용하여 fetch 함수의 비동기적 특성을 해결하려면
다음과 같은 코드를 사용할 수 있습니다.
const url
= "https://api.themoviedb.org/3/movie/550?api_key=d1015a8059e64d21776b4be2ac2efc2d";
const promise = fetch(url);
promise.then((response) => {
// 응답 객체를 처리하는 코드
});
이 코드의 경우, fetch 요청이 성공적으로 완료되면 promise 객체의 상태가 fulfilled로 변경됩니다. 그리고 promise 객체의 then 메서드가 실행되어 응답 객체를 처리하는 코드가 실행됩니다.
결론
fetch 함수는 비동기적으로 작동하는 함수입니다.
fetch 함수의 비동기적 특성을 이해하고 이를 적절하게 처리하기 위해서는
then 메서드나 Promise를 사용하는 것이 좋습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>내배캠 최고 평점 영화 콜렉션</title>
<script>
const options = {
method: "GET",
headers: {
accept: "application/json",
Authorization:
"my_api_key",
},
};
const getImageUrl = (path, size = 400) => {
return `https://image.tmdb.org/t/p/w${size}${path}`;
};
let movies;
function handleSearch(event) {
event.preventDefault(); // Prevent form submission
const searchWord = document.querySelector("#search-input").value;
// Check if movies is defined
if (!movies) {
return; // Exit the function if movies is not defined
}
const filteredMovies = movies.filter((movie) => {
return movie.title.toLowerCase().includes(searchWord.toLowerCase());
});
renderCards(filteredMovies);
}
function renderCards(movies) {
const cardList = document.querySelector(".card-list");
cardList.innerHTML = ""; // Clear existing cards
movies.forEach((movie) => {
const card = document.createElement("div");
card.classList.add("movie-card");
card.innerHTML = `
<img src="${getImageUrl(movie.poster_path)}" alt="${movie.title}">
<h3 class="movie-title">${movie.title}</h3>
<p>${movie.overview}</p>
<p>Rating: ${movie.vote_average}</p>
`;
cardList.appendChild(card);
});
}
fetch(
"https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1",
options
)
.then((response) => response.json())
.then((response) => {
// 영화 정보에서 필요한 정보를 추출한다.
const adult = response.adult;
const backdrop_path = response.backdrop_path;
const genre_ids = response.genre_ids;
const id = response.id;
const original_language = response.original_language;
const original_title = response.original_title;
const overview = response.overview;
const popularity = response.popularity;
const poster_path = response.poster_path;
const release_data = response.release_data;
const title = response.title;
const video = response.video;
const vote_average = response.vote_average;
const vote_count = response.vote_count;
// 추출한 정보를 하나의 객체에 넣는다.
const movie = {
adult,
backdrop_path,
genre_ids,
id,
original_language,
original_title,
overview,
popularity,
poster_path,
release_data,
title,
video,
vote_average,
vote_count,
};
// 객체를 콘솔에 출력한다.
console.log(movie);
const data = JSON.stringify([response]);
movies = response.results;
console.log(movies);
movies.forEach((movie) => {
const cardList = document.querySelector(".card-list");
const card = document.createElement("div");
card.classList.add("movie-card");
card.innerHTML = `
<img src="${getImageUrl(movie.poster_path)}" alt="${movie.title}">
<h3 class="movie-title">${movie.title}</h3>
<p>${movie.overview}</p>
<p>Rating: ${movie.vote_average}</p>
`;
cardList.appendChild(card);
});
})
.catch((err) => console.error(err));
</script>
</head>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.body {
background: url("../assets/bg.png") center/cover no-repeat;
min-height: 100vh;
}
.card-list {
display: grid;
grid-template-columns: repeat(3, 1fr);
justify-content: center;
}
.movie-card {
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.12), 0 3px 6px rgba(0, 0, 0, 0.24);
margin: 20px;
padding: 20px;
width: 300px;
justify-self: center;
background-color: bisque;
border-radius: 10px;
cursor: pointer;
user-select: none;
}
.movie-card img {
width: 100%;
border-radius: 10px;
}
header {
background-color: #ffe194;
display: flex;
justify-content: center;
align-items: center;
padding: 30px 0;
}
.search {
width: 100%;
display: flex;
justify-content: center;
padding: 20px 0;
border-bottom: 1px solid black;
}
.search label {
font-size: 25px;
}
.search input {
margin-left: 20px;
min-width: 200px;
padding: 5px 10px;
}
.search button {
margin-left: 10px;
padding: 5px;
}
h3 {
margin-bottom: 10px;
}
</style>
<body>
<header>
<h1>내배캠 최고 평점 영화 콜렉션</h1>
</header>
<script>
const searchInput = document.querySelector("#search-input");
if (searchInput) {
searchInput.addEventListener("input", handleSearch);
searchInput.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
alert("ENTER !!!");
}
});
}
</script>
<form class="search" onsubmit="handleSearch(event)">
<label>영화 검색 : </label>
<input
type="text"
id="search-input"
placeholder="영화 제목을 검색해 보세요"
/>
<button type="submit" id="search-btn">검색</button>
</form>
<br />
<section class="card-list"></section>
</body>
</html>
'Coding > 내일배움캠프' 카테고리의 다른 글
[내일배움캠프] Node.js 4기 TIL | Day 13 | 24.01.10.(수) (0) | 2024.01.10 |
---|---|
[내일배움캠프] Node.js 4기 TIL | 내배캠 최고 평점 영화 콜렉션 업데이트 | Day 12 | 24.01.09.(화) (0) | 2024.01.09 |
[내일배움캠프] Node.js 4기 TIL | Day 10 | 24.01.07.(일) (0) | 2024.01.07 |
[내일배움캠프] Node.js 4기 TIL | Day 09 | 24.01.06.(토) (0) | 2024.01.07 |
[내일배움캠프] Node.js 4기 TIL | Day 08 | 24.01.05.(금) (1) | 2024.01.05 |