Elice SW engineer - TIL day 16

Circlewee·2022년 4월 25일
0

Elice SW 2 TIL

목록 보기
14/31

🍑 Ajax

  • Asynchronous JavaScript And XML 의 약자. 서버와 비동기적으로 통신할 때 사용하는 API
  • 과거에는 XMLHttpRequest를 사용했지만, 현재는 fetch를 사용
const first = fetch(url);
  1. url의 주소에서 제공하는 정보를 받아와 Promise객체로 first변수에 저장함
const second = first.then(response => response.json());
  1. 첫 번째 then에서는 데이터 타입을 결정함. 이 역시 Promise객체로 저장
    json, text, xml등의 데이터 타입이 올 수 있다.
const third = second.then(data => console.log(data);
  1. 두 번째 then에서는 데이터를 전달받음. 전달 받은 데이터를 가공할 수 있음

🍑 json

  • 서로 다른 언어끼리 데이터를 주고 받을 때 사용하는 일종의 데이터 형식 혹은 포맷
    대부분의 경우 JSON type을 사용하기 때문에 아래 예시도 JSON을 이용하는 예시이다.

  • Restful API: http의 기능을 최대한 활용해서 서버와 통신할 것을 제안하는 모범사례
    url을 이용해 DB와 사용자간의 CRUD를 구현한다.

  • Create -> POST
    Read -> GET
    Update -> PUT
    Delete -> DELETE

  1. GET: API를 이용해 데이터를 받음
fetch(url)
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  1. POST: API를 이용해 데이터를 DB에 전달
fetch(url, {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  • Promise객체를 반환하고, 이것을 then method를 이용하여 출력 시 DB에 저장된 data를 반환하는 것을 알 수 있다.(사용하지 않아도 상관없음)
  1. PUT: API를 이용해 데이터를 최신화(Update)
fetch(url, {
  method: 'PUT',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  • POST와 method만 다르고 동일하다. 다만 기존 url에 존재하는 데이터를 최신화한다.
  1. DELETE
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);
});
  • 'input' 이벤트로 인해 글짜를 입력할 때마다 setTimeout이 호출된다. 만약 이것이 fetch()였다면 서버와의 불필요한 통신이 많아지기 때문에 Debouncing을 통해 해결한다.
  • 예시에서는 setTimeout의 timeoutID를 timer에 저장해서 새로이 실행될 때마다 clearTimeout을 통해 해제하는 예시이다.
let timer;
document.querySelector('.body').addEventListener('scroll', function (e) {
  if (!timer) {
    timer = setTimeout(function() {
      timer = null;
      // 실행할 코드 내용
    }, 1000);
  }
});
  • Throttling은 Debouncing과 반대되는 개념으로 특정 시간 주기로 계속 실행되는 것이다.
    보통 스크롤 이벤트에 많이 사용한다. (개인 소개 과제에도 사용)

🍑 Promise

  • 자세한 내용은 Notion에 정리함.
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
  • then method callbackfn의 인자는 resolve의 인자로 주어진 data이고
    catch method도 마찬가지이다.
profile
공부할 게 너무 많아요

0개의 댓글

관련 채용 정보