개요 |
// api.js
export async function getReviews() {
const response = await fetch("https://learn.codeit.kr/5235/film-reviews");
const body = await response.json();
return body;
}
// App.js
const handleLoadClick = async () => {
const { reviews } = await getReviews();
setItems(reviews);
};
fetch(), await을 이해 하기 위해 정리함.
fetch() |
fetch()는 JavaScript에서 네트워크 요청을 수행하는 API로, 비동기적으로 리소스를 가져올 때 사용됩니다.
Promise 기반이므로 then() 또는 async/await를 사용하여 처리할 수 있습니다.
기본문법
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json()) // JSON 변환
.then(data => console.log(data)) // 데이터 출력
.catch(error => console.error('Error:', error));
async/await 사용
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getData();
요청옵션 설정
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 })
})
.then(response => response.json())
.then(data => console.log(data));
await |
await는 JavaScript의 async 함수 내부에서만 사용할 수 있는 키워드로, 비동기 함수가 완료될 때까지 기다렸다가 그 결과를 반환합니다.
기본문법
const result = await someAsyncFunction();
- await는 Promise를 반환하는 함수 앞에 사용됩니다.
- 해당 Promise가 해결(resolve)될 때까지 기다렸다가 결과 값을 반환합니다.
- await을 사용할 때는 async 함수 내에서만 가능하며, try...catch로 오류 처리를 할 수 있습니다
사용예시
1. fetch()와 함께 사용
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error('Network error');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
2. Promise와 함께 사용
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
console.log('시작');
await delay(2000); // 2초 대기
console.log('2초 후 실행');
}
demo();
await의 특징
- 비동기 코드의 가독성을 높임 → then()을 사용한 체이닝보다 직관적
- async 함수 내부에서만 사용 가능 (await을 단독으로 사용할 수 없음)
- 동기적인 코드처럼 보이지만, 비동기적으로 실행됨
- Promise.all()과 함께 사용하면 병렬 실행 가능
async function parallelTasks() {
const [data1, data2] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/posts/1').then(res => res.json()),
fetch('https://jsonplaceholder.typicode.com/posts/2').then(res => res.json())
]);
console.log(data1, data2);
}
parallelTasks();
주의할 점
- await은 동기적인 코드 흐름을 만드므로, 여러 개의 await이 순차적으로 실행되면 성능이 저하될 수 있습니다.
- 여러 개의 독립적인 비동기 작업은 Promise.all()을 사용하여 병렬로 실행하는 것이 더 효율적입니다.
'SW Engineer & Developer > React Craft' 카테고리의 다른 글
옵셔널 체이닝(Optional Chaining) (0) | 2025.02.01 |
---|---|
React useEffect() 정리 (0) | 2025.02.01 |
arr.map() 정리 (0) | 2025.02.01 |
React 구조분해할당(Destructuring assignment) (0) | 2025.01.28 |
React 컴포넌트 트리에 데이터 공급하기 (0) | 2025.01.27 |