fetch과제

안윤경·2022년 7월 28일
0

과제

목록 보기
12/20
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
          }
        });
    })
}
  • fetch도 promise객체를 리턴한다!
  • news: json1.data에서 data는 fetch로 newsURL을 콘솔에 찍어보면 이 객체는 data라는 키에 할당이 되있는걸 볼수 있다 즉.json1.data는 객체 json의 키값이라고 봐도 될듯하다
  • 이것도 앞과 같이 마지막 return에 json1을 쓰기 위해서는 처음 then을 막으면 안된다.

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
      }
    })
}


RawBlame


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
  }
}

헷갈린점
1. 링크주소는 html script에 있으므로 모두 연결이 된다
2. fetch의 response도 임의라서 바꿔쓸수 잇는 것 같다.
3. news의 data가 있는줄 몰랐다 꼭 콘솔창에 찍어보자

profile
프론트엔드 개발자 안윤경입니다

0개의 댓글