제로하우스

[비동기 예제] fetch API를 이용한 네트워크 요청 본문

기타/코드스테이츠 블록체인 부트캠프

[비동기 예제] fetch API를 이용한 네트워크 요청

송제로투 2022. 5. 19. 01:20

📌 목적

  • fetch API를 이용해 HTTP 요청을 보내고 응답을 받는다.
  • chaining, Promise.all(), async&await를 이용한다.

 

📌 fs 모듈

비동기 요청의 가장 대표적인 사례는 네트워크 요청이며, 여기서는 fetch를 이용한 네트워크 요청에 대해서 다룬다.

let url = "<url주소>"
fetch(url)
    .then((response) => response.json())
    .then((result) => console.log(result))
    .catch((error) => throw Error(err))

 

1. basic chaining tc

fetch를 이용하여 url 주소로 데이터를 요청한다. 이후 작업을 .then으로 연결한다.

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

function getNewsAndWeather() {
  // TODO: fetch을 이용해 작성합니다
  // TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
  return fetch(newsURL)
    .then(res => res.json())
    .then(news => {
      return fetch(weatherURL)
        .then(res => res.json())
        .then(weather => {
          return {
            news: news.data,
            weather: weather
          }
        })
    })
}

getNewsAndWeather()

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

 

2. Promise.all tc

Promise.all() 메서드를 이용하여 여러 개의 데이터를 한 번에 관리한다.

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

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  return Promise.all([fetch(newsURL), fetch(weatherURL)])
    .then(([newsRes, weatherRes]) => {
      return Promise.all([newsRes.json(), weatherRes.json()])
    })
    .then(([news, weather]) => {
      return {
        news: news.data,
        weather: weather
      }
    })
}

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

 

3. async&await tc

async&await를 활용하여 데이터를 가져와서 처리한다.

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

async function getNewsAndWeatherAsync() {
  // TODO: async/await 키워드를 이용해 작성합니다
  let news = await fetch(newsURL).then(res => res.json())
  let weather = await fetch(weatherURL).then(res => res.json())

  return {
    news: news.data,
    weather: weather
  }
}

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