꾸준히 성장하는 개발자

[JavaScript] json 파일 받아오기 본문

JavaScript

[JavaScript] json 파일 받아오기

ahleum 2022. 5. 12. 15:11

1. fetch( ).then( )

fetch("https://jsonplaceholder.typicode.com/posts")
 .then((res) => {
 	return res.json();
 })
 .then((obj) => {
	 console.log(obj);
 });

 

2. axios / async await 

 

axios

Promise 기반의 HTTP 비동기 통신 라이브러리

Fetch와 Axios의 차이점은 Axios는 요청과 응답을 모두 JSON 형식으로 자동 변환시켜 줍니다.

 

async await

 Promise 객체를 사용하더라도 .then() .catch() 등등 뒤에 붙이는 것들이 많아진다. 뒤에 뭐 안 붙이고, 더 간단하게 비동기 작업을 동기적으로 만들어주는 키워드가 바로 await 이다.

  const obj = await axios.get(
  "https://jsonplaceholder.typicode.com/posts"
  );

 

 

옛날에 많이 사용하였지만 현재는 많이 사용하지 않는 방식

  const 요청객체 = new XMLHttpRequest();
  요청객체.open("GET", 요청url);
  요청객체.responseType = "json";
  요청객체.send();
  요청객체.onload = () => {
  const obj = 요청객체.response;
  할일(obj);
  };```

 


 

Promise, fetch, async await 정리한 글

https://dkfma6033.tistory.com/157

 

 

[JavaScript] Promise/ fetch / then / catch / async await

Promise :자바스크립트 비동기 처리에 사용되는 객체 Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다. 대기(pending): 이행하지도, 거부하지도 않은 초기 상태

dkfma6033.tistory.com

 

'JavaScript' 카테고리의 다른 글

[라이브러리] chart.js  (0) 2022.05.18
[라이브러리] moment cdn, npm  (0) 2022.05.17
[JavaScript] Local Storage / Session Storage  (0) 2022.04.25
[JavaScript] 타이머 함수 , 콜백(Callback)  (0) 2022.04.18
호이스팅(Hoisting)  (0) 2022.04.18