약속해줘~~그리고 fetch

야 나 개 ·2021년 11월 17일
0
post-thumbnail

new Promise 사용법에서

fetch 사용법을 보자
fetch API는 브라우저을 통해 알 수 가 있어

그래서 url로 연결하는거지

네트워크로 서버요청에서 자료를 받는거지 (이게 많이 사용하겠지?)

기본 사용방법

fetch(url)
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.log(error));

기본 연결 방법

good case

function getNewsAndWeather() {
  const newsURL = 'http://localhost:5000/data/latestNews';
  const weatherURL = 'http://localhost:5000/data/weather';

  return fetch(newsURL)
    .then((resp) => resp.json())
    .then((json1) => {
      return fetch(weatherURL)
        .then((resp) => resp.json())
        .then((json2) => {
          return {
            news: json1.data,
            weather: json2,
          };
        });
    });
}

bad case

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

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

promise all 방법

good case

function getNewsAndWeatherAll() {
  const newsURL = 'http://localhost:5000/data/latestNews';
  const weatherURL = 'http://localhost:5000/data/weather';

  return Promise.all([fetch(newsURL), fetch(weatherURL)])
    .then(([newsResponse, weatherResponse]) => {
      return Promise.all([newsResponse.json(), weatherResponse.json()]);
    })
    .then(([json1, json2]) => {
      return {
        news: json1.data,
        weather: json2,
      };
    });
}

bad case

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

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  // promise.all로 배열로 만들고, 배열의 0번째 인덱스 값을 news키값으로 하고, 1번째 인덱스 값을 웨더키값에 넣어주자.
  return Promise.all([
    fetch(newsURL).then(response => response.json()),
    fetch(weatherURL).then(response => response.json())
  ])
   .then((data) => {
      return {
       news: data[0].data,
       weather: data[1]
      }
   })
}

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

async / await 방법

good case

async function getNewsAndWeatherAsync() {
  const newsURL = 'http://localhost:5000/data/latestNews';
  const weatherURL = 'http://localhost:5000/data/weather';

  const json1 = await fetch(newsURL).then((resp) => resp.json());
  const json2 = await fetch(weatherURL).then((resp) => resp.json());

  return {
    news: json1.data,
    weather: json2,
  };
}

bad case

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

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

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

}

긴설명 안한다.

profile
야 나도 개발자 될 수 있어

0개의 댓글