Algorithm/코플릿

fetch API 과제

Summer.dev 2023. 3. 21. 22:17

 

//이부분이 어떠한 이유로 자동으로 생성되어서 테스트에서 자꾸 오류가 났었다
// 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으로 연결하여 작성합니다

  //입력: url * 2
  //출력 : {news:[{},{},{}],}
  
  let obj = {}; //빈 객체를 만들어서 나중에 값을 넣어준다.
 
  return (
    fetch(newsURL) // fetch()로 response객체를 리턴한다.
      // json()사용해서 JSON 데이터를 받아서 자바스크립트 객체로 변환한다.
      .then((response) => response.json()) // 사진첨부
      .then((response) => {
       //newsURL에 들어있는 객체의data의 값을 빈 객체 "news"키의 값으로 넣는다.
        obj.news = response.data; // {news:[{},{},{}]}
        return fetch(weatherURL); //weatherURL을 fetch한다.
      })
      //리턴값 역시 response로 json()을 통해 객체로 만들어준다.
      .then((response) => response.json())
      .then((response) => {
        obj.weather = response; //weatherURL은 단일객체 이므로 obj의 weather값으로 넣어준다.
        return obj; //완성된 객체를 리턴한다.
      })
  );
}

response.json()

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  //자바스크립트 객체형태로 만들어준다.
  const user1 = fetch(newsURL).then((response) => response.json());
  const user2 = fetch(weatherURL).then((response) => response.json());
  // 배열안에 Pormise객체를 넣어준다.
  return Promise.all([user1, user2])//[user1, user2] 모습 사진첨부
  	.then((response) => { 
    //객체에 new값으로 첫번째 url의 data값을 weather값으로 두번째 url의 객체를 넣어준다.
    return { news: response[0].data, weather: response[1] };
  });
}

Promise.all([user1, user2])의 상태

async function getNewsAndWeatherAsync() {
  // TODO: async/await 키워드를 이용해 작성합니다
  // await은 프로미스 앞에서 사용한다.
  // await 키워드는 프로미스가 settled 상태가 될 때까지 대기하다가
  // settled상태가 되면 프로미스가 resolve한 처리결과가 res변수에 할당된다.
  // 다음실행을 일시중지 시켰다가 프로미스가 settled상태가 되면 다시 제개한다.

  // json으로 프로미스를 만들어주고 await 키워드를 사용한다.
  const response1 = await fetch(newsURL).then((res) => res.json());
  const response2 = await fetch(weatherURL).then((res) => res.json());
  //response1,response2 사진첨부
  //객체에 프로퍼티를 만들어 리턴한다.
  return { news: response1.data, weather: response2 };
}

await fetch(news/weatherURL).then((res) => res.json()