2019.09.27 TIL Fetch API, Promise

Dan.kimhaejun·2019년 9월 27일
0

Dan.TIL

목록 보기
4/9

Fetch API

  1. Promise를 사용하여 구현
    • fetch(서버주소).then(콜백).then(콜백)........ .then(콜백).catch(에러콜백)
    • then의 순서로 순차적으로 진행됨
    • then과정 중 에러가 발생하면 catch로 바로 넘어가서 에러 출력

- get

  • 서버와 통신하여 받기 원하는 데이터를 요청할때 사용

  • 메소드의 default값으로 get이 설정되어 있기 때문에 바로 사용 가능

    • fetch get 사용법
fetch(http://내가get하기원하는 서버의 주소)
  .then(response => response.json()) // 콜백함수를 통해 response를 json파일로 변환
  .then(changedRes => console.log(changedRes)) // 콜백함수를 통해 변환된 파일을 콘솔에 출력
  .catch(err => console.log(err))  // then과정중 에러가 발생하면 catch로 넘어가 에러 출력
- 예
fetch('https://koreanjson.com/posts/1')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log(error));
  • 결과
{
  "id": 1,
  "title": "정당의 목적이나 활동이 민주적 기본질서에 위배될 때에는 정부는 헌법재판소에 그 해산을 제소할 수 있고, 정당은 헌법재판소의 심판에 의하여 해산된다.",
  "content": "모든 국민은 인간으로서의 존엄과 가치를 가지며, 행복을 추구할 권리를 가진다. 모든 국민은 종교의 자유를 가진다. 국가는 농·어민과 중소기업의 자조조직을 육성하여야 하며, 그 자율적 활동과 발전을 보장한다. 모든 국민은 양심의 자유를 가진다. 누구든지 체포 또는 구속을 당한 때에는 즉시 변호인의 조력을 받을 권리를 가진다.",
  "createdAt": "2019-02-24T16:17:47.000Z",
  "updatedAt": "2019-02-24T16:17:47.000Z",
  "UserId": 1
}
- 에러 (3번줄 console의 e없음) 
fetch('https://koreanjson.com/posts/1')
  .then(response => response.json())
  .then(json => consol.log(json))
  .catch(error => console.log(error));
- 에러 결과
ReferenceError: consol is not defined
    at <anonymous>:3:22
- 참조 (정상실행, 에러)

2. Promise 객체

new Promise(resolve => {
	resolve(100)
}).then(res => {
	console.log(res)
	return res + 100;
}).then(res => {
	console.log(res)
}).catch(err => console.error(err));

출처: Korean JSON
https://koreanjson.com/

profile
제가 겪은 이슈에 대해서 정리합니다. 기억보다는 기록이 더 낫다고 생각합니다.

0개의 댓글