0119 TIL ; fetch

돌리의 하루·2023년 1월 19일
0

오늘은 fetch를 이용한 네트워크 요청을 배웠다!

fetch란?

예로 들어보면

fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data));

이렇게 설명할 수 있겠다.
fetch를 사용할 땐 두 단계를 거쳐야 한다. 먼저 올바른 url로 요청을 보내야 하고, 바로 뒤에오는 응답에 대해 json()을 해줘야한다.

fetch(url) > response된 promise 객체로 반환
.then으로 json메서드 사용

‼️여기에서 잠깐!!!!! json이란?

자바스크립트 객체 표기법과 아주 유사하다. json의 문서 형식은
자바스크립트 객체의 형식을 기반으로 만들어졌다.
문법은 이렇게 나타낸다.

{
"employees": [
  {
    "name": "Surim",
    "lastName": "Son"
  },
  {
    "name": "Someone",
    "lastName": "Huh"
  },
  {
    "name": "Someone else",
    "lastName": "Kim"
  } 
]
}

JSON 형식은 자바스크립트 객체와 마찬가지로 key / value가 존재할 수 있으며 key값이나 문자열은 항상 쌍따옴표를 이용하여 표기해야한다.

서버에서 날씨를 받아온 후 요청의 결과를 두 개의 요청을 하나로 합치는것이 목표이다.
이 과정을 총 3번 반복했는데, 각각 다른 방법으로 코드를 작성해봤다.

각각 fetch, promise.all, async,await을 사용했다.

  1. fetch 사용
const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';
//위에서 링크를 받아옴
function getNewsAndWeather() {
 
  return fetch(newsURL)//url로 링크를 받고 promise타입 객체반환
  .then((resp)=> resp.json())
  .then((news)=> {//(1)
   
    return fetch(weatherURL)
    .then((respweather)=> respweather.json())
    .then((weather)=>{
      //(2))
      return {
        news : news.data,
        weather : weather
      }
     
    })
    
  })
}
//(3)
if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeather
  }
}

//(1) { data : news } (구조분해할당)으로 이렇게도 쓸 수 있다! (=news.data)
then의 인자인 news는 fetch(newURL)을 받는다.
fetch(newURL)는 json()메서드를 거친상태이다.
또한, (2)의 weather과 같이 써주기 위해서 {}을 열고 return 후 fetch(weatherURL)에
똑같은 작업을 해주고 있다! 괄호에 신경써주기! 이 부분에서 조금 헤맸다 😂

//(2) news : news.data,
weather : weather를 반환해주고 있는 모습.
여기서 news에만 왜 .data를 붙여줬냐면, console.log로 찍어보면 알 수 있다.

이런식으로 news.data에 array가 들어가 있는 모습을 볼 수 있다.

//(3) typeof window === 'undefined'
이 부분이 뜻하는 바는 무엇일까!
바로 브라우저가 렌더링 되었을때를 나타낸다.

2.promise.all 사용

function getNewsAndWeatherAll() {
    let news = fetch(newsURL).then((res)=>res.json()).then((res)=> res.data);
    let weather = fetch(weatherURL).then((res)=> res.json())

    return Promise.all([news,weather])
    .then((something)=> {//(1)
      let news = something[0]//(2)
      let weather = something[1]//(3)
        return {
          //(4)
          news : news,
          weather : weather
        }
    })
  }

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

//(1) news,weather을 배열로 담아준값
//(2),(3) 헷갈린다면 something을 console.log로 찍어보면 확실히 알 수 있다!
//(4)return { news : weather }로 쓸 수 있다 ( 구조분해할당 )

  1. async,await
async function getNewsAndWeatherAsync() {
  
  const news = await fetch(newsURL) //(1)
  .then((res)=>res.json())
  .then((res)=>res.data);
  const weather = await fetch(weatherURL).then((res)=>res.json());


  return {
    news:news,
    weather:weather
  }
}
if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAsync
  }
}

//(1)const{news.data} = await fetch(newsURL)로도 쓸 수 있다!
async,await은 아주 유용하게 쓰인다! 코드도 훨씬 간결해지고, 사용법도 쉽다. 쓰면서 이렇게 코드가 간단해지다니! 하고 놀랐다...!🤩

profile
진화중인 돌리입니다 :>

0개의 댓글