Node.js - fetch API

김도영·2022년 5월 24일
0
post-thumbnail

fetch API

비동기의 가장 대표적인 사례는 '네트워크 요청'인데, URL로 요청을 가능하게 해주는 API가 바로 'fetch API'이다.

예를 들어, 어느 한 포털 사이트에서 시시각각 변화는 정보와, 늘 고정적인 정보가 따로 분리되어 있다. 이 중에서 최신 뉴스나 날씨정보는 동적으로 데이터를 받와야 하는 정보이다. 이 때, 많은 웹사이트에서 해당 정보만 업데이트 하기 위해 요청 API를 이용 해야 하는데 여기서 fetch API를 이용한다. fetch API는 특정 URL로부터 정보를 받아오는 역할을 한다. 이 과정이 비동기로 이루어지기 때문에, 경우에 따라 다소 시간이 걸릴수 도 있다.

fetch API 실습 - basciChaining.js

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

function getNewsAndWeather() {
  // 여러개의 Promise를 then으로 연결하여 작성
  let result = {};
  return fetch(newsURL)
  .then( data => data.json() )
  .then( newsdata => {
    result.news = newsdata.data
    return fetch(weatherURL)
    .then( data => data.json() )
    .then( weatherdata => {
      result.weather = weatherdata
      return result;
    })
  })
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeather
  }
}

promiseALL.js

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

function getNewsAndWeatherAll() {
  // Promise.all을 이용해 작성
  let result = {};
  let news = fetch(newsURL).then( (data) => data.json() )
  let weather = fetch(weatherURL).then( (data => data.json() ))

  return Promise.all( [news, weather] )
  .then( (data) => {
    result.news = data[0].data;
    result.weather = data[1];
    return result;
  })
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAll
  }
}

asyncAwait.js

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

async function getNewsAndWeatherAsync() {
  // async, await를이용해 작성
  let news = await fetch(newsURL).then( (data) => data.json() )
  let weather = await fetch(weatherURL).then( (data => data.json() ))
  return {
    news:news.data,
    weather:weather
  }
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAsync
  }
}
profile
Blockchain Developer

0개의 댓글