Fetch API 코드 셀프 리뷰

semin·2023년 5월 17일

section 2

목록 보기
1/6
post-thumbnail

Fetch API 의사코드와 느낀점...

part-3/01_basicChaining

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

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

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

/* pseudo code
1. newsURL에서 latestNews 가져오기
2. json1 = parsed news data
3. weatherURL에서 weather data 가져오기
4. json2 = parsed weather data
5. result = {
     news: json1.data,
     weather: json2
   }
6. return result
*/

// refe 보기 전에 작성한 코드

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

function getNewsAndWeather() {
  // fetch: 비동기적으로 데이터를 가져올 수 있게 하는 브라우저 API

  let newsData;
  let weatherData;

  return fetch(newsURL)
    .then((newsResponse) => newsResponse.json()) // 응답 내용을 json으로 받아야 사용 가능... 왜지?
    .then((data) => {
      newsData = data.data; // newsData에 data.data를 할당하여 news 배열을 저장 (url 내부 객체에 data로 한 번 더 감싸져 있다)
      return fetch(weatherURL); // 뉴스 읽은 후에 날씨 읽으라고 보냄
    })
    .then((weatherResponse) => weatherResponse.json())
    .then((data) => {
      weatherData = data;
      const result = {
        news: newsData, //  테스트 코드에서 원하는 형식
        weather: weatherData,
      };
      return result;
    });
}

if (typeof window === "undefined") {
  module.exports = {
    getNewsAndWeather,
  };
}

차이점

  1. 변수 선언 방식
    var는 함수 스코프를 가지고 있어 한 번만 선언해도
    script로 뒤에 연결된 파일끼리 url를 읽어오는구나...
    나는 const와 let을 사용해서 (블록 스코프)
    뒤의 과제에서 fetch 관련 변수를 계속 선언해야 했다.

  2. Promise 체이닝
    나는 중간에 변수를 사용하여 데이터를 저장했다.
    부수적 선언 없이, 나온 값에 바로 체이닝이 훨씬 깔끔한 듯.

part-3/02_promiseAll

// refe code

function getNewsAndWeatherAll() {
  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
      }
    })
}

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

/* pseudo code
1. latestNews와 weather data 가져오기 위해 fetch를 사용, 요청 전송
2. response data를 Promise로 처리해서 parse
3. parsed news data + parsed weather data를 return
*/

// 내 코드

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  const newsPromise = fetch("http://localhost:4999/data/latestNews")
    .then((response) => response.json()) 
    .then((data) => data.data);

  const weatherPromise = fetch("http://localhost:4999/data/weather").then(
    (response) => response.json()
  );

  return Promise.all([newsPromise, weatherPromise]).then( 
    ([newsData, weatherData]) => {
      const mergedData = {
        news: newsData,
        weather: weatherData,
      };
      return mergedData;
    }
  );
}

if (typeof window === "undefined") {
  module.exports = {
    getNewsAndWeatherAll,
  };
}

차이점

  1. Promise 체이닝
    Promise.all을 사용해서 데이터들을 동시에 가져오고,
    그 후에 파싱함.
    나는 개별적인 Promise를 생성 후 병렬로 실행함 (번잡)

  2. 변수 사용 방식
    중첩된 then 블록 내 변수로 데이터 저장하면 깔끔!
    나는 다 변수로 선언시키고
    Promise.all 써서 병렬 처리 및 리턴함. 비효율적이다…

part-3/03_asyncAwait

// refe code (진짜 너무 깔끔해서 기절함)

async function getNewsAndWeatherAsync() {

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

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

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

/* pseudo code
1. latestNews와 weather data 가져오기 위해 fetch를 사용, 요청 전송
2. response data를 `resp` 변수에 저장
3. `resp` 변수에서 JSON 데이터를 뽑아다가 `json1` || `json2` 변수에 할당
4.  return result
*/

// 내... 코드...

async function getNewsAndWeatherAsync() {
  try {
    const newsPromise = fetch("http://localhost:4999/data/latestNews");
    const weatherPromise = fetch("http://localhost:4999/data/weather"); // 코드 길어지기 싫으니까 미리 링크 선언해 놓고

    const [newsResponse, weatherResponse] = await Promise.all([newsPromise, weatherPromise]); // await 써서 둘 다 성공적으로 받아올 때까지 기다려

    const [newsData, weatherData] = await Promise.all([
      newsResponse.json(),
      weatherResponse.json()
    ]); 

    const mergedData = { 
      news: newsData.data,
      weather: weatherData
    };

    return mergedData;
  } catch (error) {
    throw error;
  }
}

if (typeof window === "undefined") {
  module.exports = {
    getNewsAndWeatherAsync,
  };
}

차이점

  1. 비동기 처리 방식
    await에 then 써도 되는 줄 몰랐다…
    (말도 안 되는 변명)

  2. 오류 처리
    await에 then을 쓰니까 가독성이 높아짐
    -> try-catch 안 써도 된다.

  3. 변수 선언 방식
    나는 변수 선언과 초기화를 동시에 하기 위해
    const 에 할당 연산자를 사용했는데,
    let 사용해서 변수 선언, 코드 내에서 변수 초기화를 하심.
    하...

  4. 네트워크 요청 처리
    Promise.all로 병렬 처리한 나…
    그냥 체이닝으로 스무스하게 엮을 수 있구나…

0개의 댓글