종우의 컴퓨터 공간
★[ES6]Fetch API 본문
예제
// Get local text file data
document.getElementById('button1').addEventListener('click', getText);
function getText() {
fetch('test.txt')
.then(function(res) {
return res.text();
})
.then(function(data) {
console.log(data);
document.getElementById('output').innerHTML = data;
})
.catch(function(err) {
console.log(err);
});
}
// Get local json data
document.getElementById('button2').addEventListener('click', getJson);
function getJson() {
fetch('posts.json')
.then(function(res) {
return res.json();
})
.then(function(data) {
console.log(data);
let output = '';
data.forEach(function(post) {
output += `<li>${post.title}</li>`;
})
document.getElementById('output').innerHTML = output;
})
.catch(function(err) {
console.log(err);
});
}
// Get from external API
document.getElementById('button3').addEventListener('click', getExternal);
function getExternal() {
fetch('https://api.github.com/users')
.then(function(res) {
return res.json();
})
.then(function(data) {
console.log(data);
let output = '';
data.forEach(function(user) {
output += `<li>${user.login}</li>`;
})
document.getElementById('output').innerHTML = output;
})
.catch(function(err) {
console.log(err);
});
}
- fetch()는 Promise를 return 하기에 .then()과 .catch()를 사용해야한다.
- text 파일의 경우 fetch()를 했을 때 response.text()가 promise 이기 때문에 return 해서 또 .then()과 .catch()를 사용하고, json과 external API 같은 경우에도 fetch()를 했을 때 response.json()이 promise이기 때문에 동일한 방법으로 사용한다.
'자바 스크립트 (JavaScript) > Asynchronous JS, Ajax & Fetch API' 카테고리의 다른 글
[ES6]Custom HTTP Library (Fetch with Promises) (0) | 2021.08.16 |
---|---|
★[ES6]Arrow Functions (0) | 2021.08.13 |
★[ES6] Promises (0) | 2021.08.11 |
Custom HTTP Library (Ajax with Callbacks) (0) | 2021.08.11 |
Callback Functions (0) | 2021.08.11 |