(ES6+) ajax를 위한 fetch와 async/await
이 글을 읽기 전에 (ES6) ajax 위주의 promise 실습를 먼저 읽을 것을 권한다.
ajax(XMLHttpRequest)와 promise에 대한 기본적인 이해가 있다면 상관없긴 하다.
조현영 님의 제보에 의하면 ie에서 fetch가 안 되고,
async/await 크롬과 오페라에서만 된다고 한다.
아래 사이트에서 확인 가능하다.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#Browser_compatibility
ECMAScript Next compatibility table
fetch
다시 공부하다보니 XMLHttpRequest와 Fetch는 ECMAScript가 아니라고 한다.
브라우저에서만 쓰이는 API이기 때문에 babel에서도 지원해주지 않기 때문에
크로스 브라우징을 위해선 window.fetch polyfill을 쓰자.
우선 기존에 우리가 ajax를 하기 위해서 어떻게 했는지 보자.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22const jsonURL = "https://perfectacle.github.io/mock/test.json";
const getDataAjax = url => {
const xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "json";
xhr.onreadystatechange = () => {
if(xhr.readyState === 4) { // 4 means request is done.
if(xhr.status === 200) { // 200 means status is successful
for(let key in xhr.response) { // 받아온 json 데이터의 키와 값의 쌍을 모두 출력.
if(xhr.response.hasOwnProperty(key))
console.log(`${key}: ${xhr.response[key]}`);
}
} else { // 통신 상에 오류가 있었다면 오류 코드를 출력.
console.error(`http status code: ${xhr.status}`);
}
}
};
xhr.send();
};
getDataAjax(jsonURL);
