const first = fetch(url);
const second = first.then(response => response.json());
const third = second.then(data => console.log(data);
서로 다른 언어끼리 데이터를 주고 받을 때 사용하는 일종의 데이터 형식 혹은 포맷
대부분의 경우 JSON type을 사용하기 때문에 아래 예시도 JSON을 이용하는 예시이다.
Restful API: http의 기능을 최대한 활용해서 서버와 통신할 것을 제안하는 모범사례
url을 이용해 DB와 사용자간의 CRUD를 구현한다.
Create -> POST
Read -> GET
Update -> PUT
Delete -> DELETE
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
})
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log(data)
})
fetch(url, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log(data)
})
fetch(url, {
method: 'DELETE',
})
.then(response => response.json())
.then(data => {
console.log(data)
})
PUT, POST와 다르게 headers, body가 필요없다. DB에 존재하는 해당 데이터를 삭제하며 빈 객체를 반환한다.
json server 여는법
간단하게 Promise, fetch등을 연습해볼 수 있다.
npx json-server --watch (파일 명)
js는 기본적으로 동기언어. 다만 비동기 함수를 사용하면 비동기로 동작한다.(오늘 실습의 키워드)
Debouncing & Throttling
let timer;
document.querySelector('#input').addEventListener('input', function(e) {
if(timer) {
clearTimeout(timer); -> timer의 setTimeout을 취소시킴
}
timer = setTimeout(function() {
// 실행 코드 내용
}, 1000);
});
let timer;
document.querySelector('.body').addEventListener('scroll', function (e) {
if (!timer) {
timer = setTimeout(function() {
timer = null;
// 실행할 코드 내용
}, 1000);
}
});
new Promise((resolve, reject) => {
let data = [1,2,3];
if (!error) {resolve(data)}
else {reject('ERROR')}
})
.then(data => console.log(data) // [1, 2, 3]
.catch(err => console.log(err) // ERROR