Fetch API

Jiyoung·2020년 12월 24일
0

비동기 요청의 가장 대표적인 사례를 꼽으라고 한다면, 단연 네트워크 요청을 들수 있다. 다양한 네트워크 요청 중, URL로 요청하는 경우가 가장 흔하다. 이를 가능하게 해주는 API가 바로 Fetch API이다.

어떤 포털 사이트에서 시시각각 변하는 정보와 늘 고정적인 정보가 분리되어 있다면, 시시각각 변하는 정보, 즉 최신 뉴스나 날씨 정보 등이 바로 동적으로 데이터를 받아와야 하는 정보이다. 이때 해당 정보만 업데이트하기 위해 자바스크립트, 그 중에서도 Fetch API를 이용해 해당 정보를 원격 URL로 불러온다.

Fetch API는 특정 URL로부터 정보를 받아오는 역할을 해주며, 이 과정이 비동기로 이루어지기 때문에 다소 시간이 걸리는 작업을 요구할 경우, blocking(동기적인 처리)이 발생하면 안되기 때문에 특정 DOM에 정보가 표시될때까지 로딩창을 대신 띄우는 경우도 많이 있다.

Fetch API 사용법

Fetch API는 Promise 형식으로 이루어져있다.

let url = 'http://example.com/최신뉴스';
fetch(url)
  .then(response => response.json()) // 자체적으로 json() 메소드가 있어, 응답을 JSON 형태로 변환시켜서 다음 Promise로 전달합니다
  .then(json => console.log(json)) // 콘솔에 json을 출력합니다
  .catch(error => console.log(error)); // 에러가 발생한 경우, 에러를 띄웁니다

아래는 스프린트에서 작성한 코드.

var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';

function getNewsAndWeather() {
  return fetch(newsURL)
    .then(response => response.json())
    .then((json1) => {
      return fetch(weatherURL)
        .then(response => response.json())
        .then((json2) => {
          return {
            news: json1.data,
            weather: json2
          }
        })
    })
}

위처럼 fetch API를 이용하면 특정 URL로부터 다음과 같은 뉴스와 날씨 정보를 받아오게 된다.

const obj = {
  news: [{ row_id: 2, title: "2021년 경제 성장률 전망 밝아", source: "A신문", timestamp: "2020/12/30" },
  { row_id: 3, title: "코로나19 증가추세 대폭 하락해", source: "BBC", timestamp: "2020/12/29" },
  { row_id: 4, title: "코드스테이츠 취업연계 파트너사 xxx건 돌파", source: "스타트업 뉴스", timestamp: "2020/12/31" }],

  weather: { status: "sunny", tempature: "28", finedust: "good" }
};

Promise.all을 사용하여 여러 개의 Promise를 처리할 수 있다.

function getNewsAndWeatherAll() {
  let news = fetch(newsURL)
    .then(response => response.json());
  let weather = fetch(weatherURL)
    .then(response => response.json());
  return Promise.all([news, weather])
    .then(values => {
      return {
        news: values[0].data,
        weather: values[1]
      };
    })
}

Async/Await키워드를 사용하면 코드를 좀 더 간결하게 표현할 수 있다.

async function getNewsAndWeatherAsync() {
  let json1 = await fetch(newsURL)
    .then(response => response.json());
  let json2 = await fetch(weatherURL)
    .then(response => response.json());

  return {
    news: json1.data,
    weather: json2
  }
}
profile
경계를 넘는 삶

0개의 댓글