fetch()
기본적인 fetch 결과 호출
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| async function getTodoData() { const response = await fetch("https://jsonplaceholder.typicode.com/todos/1"); const jsonData = await response.json(); return jsonData; }
const getFetchData = async () => { const result = await getTodoData(); console.log(result); }
getFetchData(); /* { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } */
|
fetch 오류 처리
HTTP 오류 : 정상적으로 응답은 오지만 결과적으로 오류인 경우
네트워크 오류 : 서버다운, 도메인 없음처럼 요청 자체가 실패하는 경우
async/await + try…catch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { // HTTP 상태 코드가 200-299가 아닐 때 throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); console.log('Data:', data); } catch (error) { console.error('Network error:', error.message); } }
fetchData();
|
.then().catch()
1 2 3 4 5 6 7 8 9 10 11 12 13
| fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log('Data:', data); }) .catch(error => { console.error('Network error:', error.message); });
|
Promise.all()
여러 개의 호출을 병렬로 실행합니다. 모두 완료될때까지 기다렸다가 결과를 반환합니다. 하나라도 실패하면 전체 실패로 간주하여 catch가 실행됩니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const fetchUser = () => Promise.resolve('User data'); const fetchPosts = () => Promise.resolve('Posts data'); const fetchComments = () => Promise.resolve('Comments data');
Promise.all([fetchUser(), fetchPosts(), fetchComments()]) .then(([user, posts, comments]) => { console.log(user); // 'User data' console.log(posts); // 'Posts data' console.log(comments); // 'Comments data' }) .catch(err => { console.error('Fetch error:', err); }); // User data // Posts data // Comments data
|
Promise.allSettled()
성공/실패 여부와 상관없이 결과를 반환합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const fetchUser = () => Promise.resolve('User data'); const fetchPosts = () => Promise.resolve('Posts data'); const fetchComments = () => Promise.resolve('Comments data');
Promise.allSettled([fetchUser(), fetchPosts(), fetchComments()]) .then(results => { console.log(results); });
/* [ { "status": "fulfilled", "value": "User data" }, { "status": "fulfilled", "value": "Posts data" }, { "status": "fulfilled", "value": "Comments data" } ] */
|
동적으로 생성된 비동기 처리
1 2 3 4 5 6 7 8
| const ids = [1, 2, 3];
const promises = ids.map(id => fetch(`/api/item/${id}`).then(res => res.json()));
Promise.all(promises) .then(results => { console.log(results); // 각 id에 대한 응답 });
|
async/await + allSettled()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| const user = ref(null) const posts = ref(null) const comments = ref(null) const errors = ref([])
const fetchData = async () => { const requests = [ axios.get('/api/user'), axios.get('/api/posts'), axios.get('/api/comments') ]
const results = await Promise.allSettled(requests)
results.forEach((res, index) => { if (res.status === 'fulfilled') { switch (index) { case 0: user.value = res.value.data break case 1: posts.value = res.value.data break case 2: comments.value = res.value.data break } } else { errors.value.push({ index, message: res.reason?.message || 'Unknown error' }) } }) }
onMounted(() => { fetchData() })
|
map + allSettled()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| const results = ref([]) const errors = ref([])
// 요청할 API 목록 (이름과 endpoint를 함께 저장) const apiList = [ { name: 'user', url: '/api/user' }, { name: 'posts', url: '/api/posts' }, { name: 'comments', url: '/api/comments' } ]
const fetchData = async () => { // 각 API를 axios로 요청하는 배열 생성 const requests = apiList.map(api => axios.get(api.url))
// allSettled로 모든 요청 결과 처리 const responses = await Promise.allSettled(requests)
// 이름을 매핑해서 결과 정리 responses.forEach((res, i) => { const { name } = apiList[i]
if (res.status === 'fulfilled') { results.value.push({ name, data: res.value.data }) } else { errors.value.push({ name, message: res.reason?.message || 'Unknown error' }) } }) }
onMounted(() => { fetchData() })
|