Daily Front_Minhhk

[JS] fetch API...sprint 본문

Code개발일지

[JS] fetch API...sprint

Minhhk 2022. 11. 25. 22:19

fetch API는 특정 URL로 부터 정보를 받아오는 역할을 합니다. 이 과정은 비동기적으로 이루어집니다.

let url =
  "<https://v1.nocodeapi.com/codestates/google_sheets/YbFMAAgOPgIwEXUU?tabId=최신뉴스>";
fetch(url)
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.log(error));

위 코드는 네트워크에서 JSON 파일을 가져와서 콘솔에 출력합니다.

가장 단순한 형태의 fetch()는 가져오고자 하는 리소스의 경로를 나타내는 하나의 인수만 받습니다.

응답은 Response 객체로 표현되며, 직접 JSON 응답 본문을 받을 수는 없습니다.

Response 객체 역시 JSON 응답 본문을 그대로 포함하지는 않습니다.

Response는 HTTP 응답 전체를 나타내는 객체로, JSON 본문 콘텐츠를 추출하기 위해서는 json() 메서드를 호출해야 합니다.

json()은 응답 본문 텍스트를 JSON으로 파싱한 결과로 이행하는, 또 다른 프로미스를 반환합니다.


01_basicChaining.js

// const { response } = require("express");

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

function getNewsAndWeather() {
  // TODO: fetch을 이용해 작성합니다
  // TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
  return fetch(newsURL)
  .then(resp => resp.json()) // promise 반환 > url1 으로 임의지정 > 접근
  .then(url1 => {
    // url1 -> 받아온 newsURL
    return fetch(weatherURL) // 체이닝
      .then(resp => resp.json()) // promise 반환 > url2 으로 임의지정 > 접근
      // url2 -> 받아온 weatherURL
      .then(url2 => {
        return { //! 하나의 객체 생성
          news: url1.data,   // 테스트의 key === news, value === data (app.js -> data)
          weather: url2 
        }
      });
    })
}

getNewsAndWeather()

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

다른방법

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

function getNewsAndWeatherFunc() {

    let final = {};

    return fetch(newsURL)
        .then(res=>res.json())
        .then((result) => {
          final.news = result.data;
          return fetch(weatherURL)
        })    
        .then(res => res.json())
        .then(result => {
          final.weather = result;
          return final
        })
}

02_promiseAll.js

const url1 = fetch(newsURL).then(res=>res.json()).then((result)=>result.data)
const url2 = fetch(weatherURL).then(res=>res.json())

function getNewsAndWeatherAll() {
  // console.log(url1) // -> promise 
  // console.log(url2) // -> promise 

  return Promise.all([url1,url2])
          .then((value)=>{ // value 에 값을 담아준다 > 배열 
            console.log(value)
            return { //! 한 객체로 생성
              news : value[0] , // 가져온 값에서 0번째
              weather : value[1] // 가져온 값에서 1번째 출력
            }
          })
}

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

03_asyncAwait.js

const news1 = fetch(newsURL).then(res=>res.json()).then((result)=>result.data)
const weather2 = fetch(weatherURL).then(res=>res.json())

async function getNewsAndWeatherAsync() {
  // TODO: async/await 키워드를 이용해 작성합니다
  let a = await news1
  let b = await weather2

  return { // ! 한 객체 생성
    news : a ,
    weather : b
  }
}

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