비동기 계속~
지난 글에서 XmlHttpRequest를 사용해 통신하는 방법을 알아 봤는데
그 보다 간단한 fetch, 또 그 보다 더 간단한 axios에 대해 작성할 예정!
Fetch api는 web에 기본적으로 포함 되어 있는 Ajax 구현 방법 중 하나
fetch() 함수 형태로 사용const data = {
...
}
const url = 'https://api';
const options = {
method: 'GET',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
//...
}
const promise = fetch(url, options)
promise.then((response)=>{
// 응답 데이터 처리 로직
}).catch((error)=>{
// 에러 발생 시 처리 로직
})
send() 메서드를 실행해야 전송됨const request = new XMLHttpRequest()
request.open('GET', 'https://api.github.com/users/soohyn/repos')
request.addEventListener('load', (e) => {
console.log(JSON.parse(e.target.response))
// 데이터 처리 로직
})
request.send()
then() 메서드가 알아서 실행 됨send() 메서드를 따로 실행할 필요없이 fetch() 함수 실행과 동시에 생성, 구성, 전송 실행fetch('https://api.github.com/users/soohyn/repos',{
method: 'GET'
}).then(()=>{}).catch(()=>{})
function count(callback) {
if(!callback) return
setTimeout(console.log(n), 1000)
}
count(count(count(count())))
function runEvery1000ms() {
return new Promise((resolve, reject)=>{
if(!callback) reject(new Error('error'))
setTimeout(resolve,1000)
})
}
runEvery1000ms
.then(runEvery1000ms)
.then(runEvery1000ms)
.then(runEvery1000ms)
new Promise((resolve, reject)=>{
if(조건) resolve('성공!') // then 실행
else reject('실패!') // catch 실행
})
const promise = fetch(URL) // pending
const response = promise
.then(()=>{}) // fulfilled
.catch(()=>{}) // rejected

const promise = fetch("https:// api.github.com/users/soohyn");
promise
.then((response)=>{
if(!response.ok) throw new Error()
return response.json()
}).then((data)=>{
// 데이터 가공 로직 삽입 가능
return { data }
})catch((error)=>console.error(error))
ReadableStream라는 형태로 되어있어 자바스크립트에서 사용 불가, 별도의 처리가 필요

Ajax 통신을 편리하게 하기 위해 나온 라이브러리
import axios from 'axios'
axios.get(URL,{ params: {} })
axios.post(URL,{ name: 'soohyun', color: 'cyan' })
axios.put(URL,{ name: 'soohyn', color: 'magenta' })
axios.patch(URL,{ color: 'yellow' })
axios.delete(URL)
const API_ENDPOINT = "https://dummyjson.com/products";
const product = {
title: "더블링 소세지",
price: 6200,
};
axios
.post(`${API_ENDPOINT}/add`,product)
.then(({ data }) => {
console.log(data);
})
.catch(console.error);
data 출력
fetch(`${API_ENDPOINT}/add`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(product),
})
.then((response) => {
return response.json().then((body) => {
if (!response.ok) return Promise.reject(body);
return body;
});
})
.catch(console.error);
| fetch | axios | |
|---|---|---|
| 데이터 처리 | JSON.stringify 사용, json() 메서드 사용 | 자바스크립트 객체 사용 |
| 에러 처리 | 상태 코드에 따라 개발자가 직접 작성 | 에러 발생 시 알아서 catch로 보내줌 |
| 복잡도 | 비교적 복잡함 | 비교적 간편함 |
비동기도 뭔가 볼 때마다 새로운 느낌 ... 이러면 안 되는데~~