종우의 컴퓨터 공간

★[ES6]Fetch API 본문

자바 스크립트 (JavaScript)/Asynchronous JS, Ajax & Fetch API

★[ES6]Fetch API

종우공간 2021. 8. 13. 01:52

예제

// 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이기 때문에 동일한 방법으로 사용한다.