본문 바로가기
💻/[과제]

[과제] Part 3 - fetch API

by Mia_ 2022. 11. 23.

fetch API

: URL 주소를 통해 서버로부터 동적으로 데이터를 받아오는 API

 

- fetch API 특정 URL로부터 정보를 받아오는 역할을 함

- 이 과정이 비동기로 이루어지기 때문에 경우에 따라 다소 시간이 걸릴 수 있음

- 이렇게 시간이 소요되는 작업을 요구할 경우 blocking이 발생하면 안되므로 특정 DOM에 정보가 표시 될 때 까지 로딩 창을 띄우는 경우도 있음

 

 

- fetch()를 불러들이는 경우, 취득한 리소스를 반드시 인수로 지정하지 않으면 안됨!

- 읽어들인 뒤, fetch()는 Promise객체를 반환

- 리퀘스트가 실패하든 해당 리퀘스트 통신에 대한 response 객체가 취득

 

- response를 가져온 후에, 콜백 함수의 매개변수로 담긴 response 객체는 리스폰스에 포함되어 있는 컨텐츠와 그에 대한 처리 방법이 담긴 메소드들이 담겨 있음


Bare Minimum requirements

 

Chaining Test
getNewsAndWeather

- 체이닝 결과가 Promise 형태로 리턴되야 함

- /data/latest의 응답 내용과 /data/weather 응답 내용을 합쳐 새로운 객체로 리턴 되야함

- fetch를 활용. 총 두 번 사용해야 함

- Promise.all 또는 async/await을 사용하지 않고 풀이

 

- fetch를 불러들이는 경우 취득한 리소스를 반드시 인수로 지정

- 읽어 들인 뒤 fetch()는 promise 객체를 반환함

- 리퀘스트가 실패하든 해당 리퀘스트 통신에 대한 값을 response가 취득함 

function getNewsAndWeather() {

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

  return fetch(newsURL)
  .then( res => res.json())
  .then( newsdata => {
    let news = newsdata.data
    return fetch(weatherURL)
    .then((res) => {
      return res.json()
    }).then( weatherdata => {
      let weather = weatherdata
      return {
        news : news,
        weather : weather
      }
    })
  }) 

}

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

- newsURL을 가져와서 JSON 형태로 변형해서 봤을 때 객체 안에 key 이름이 data라는 이름으로 저장된 것이 확인 됨

 

 

Promise.all Test
getNewsAndWeatherAll

- Promise 형태로 리턴되어야 함

- Promise.all을 사용해서 풀어야 함

- /data/latest의 응답 내용과 /data/weather 응답 내용을 합쳐 새로운 객체로 리턴

function getNewsAndWeatherAll(){

  const newsURL = 'http://localhost:4999/data/latestNews';
  const weatherURL = 'http://localhost:4999/data/weather';
  
  
    let news = fetch(newsURL).then((response) => response.json())//취득 내용을 news로 받음
    let weather = fetch(weatherURL).then((response) => response.json())
    
    return Promise.all([news, weather])
    .then((res) => {
      let news = res[0]
      let weather = res[1]
      return {
        news : news.data,
        weather : weather
      }
    })

}

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

- Promise.all로 배열 형태로 가져온 response임!

 

 

async/await Test
getNewsAndWeatherAsync

- async 키워드를 사용한 함수는 AsyncFunction의 인스턴스임

- /data/latest의 응답 내용과 /data/weather 응답 내용을 합쳐 새로운 객체로 리턴

- async/await을 활용해야 함. 총 두 번 사용해야함

async function getNewsAndWeatherAsync() {

  const newsURL = 'http://localhost:4999/data/latestNews';
  const weatherURL = 'http://localhost:4999/data/weather';
  
  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
  }
}

'💻 > [과제]' 카테고리의 다른 글

[과제] Message States  (0) 2022.12.02
[과제] React Twittler Intro  (0) 2022.11.25
[과제] Part 1 - 타이머 API  (0) 2022.11.22
[과제] Underbar  (0) 2022.11.22
[과제] localStorage 와 JSON  (0) 2022.11.15