section2 Fetch API

유희준·2023년 3월 21일

section2

목록 보기
6/12
var newsURL = 'http://localhost:4999/data/latestNews';
var weatherURL = 'http://localhost:4999/data/weather';
//fetch는 fetch API는 특정 URL로 부터 데이터를 받아오는 역할을 한다.
function getNewsAndWeather() {
  return fetch(newsURL) // url 정보가져옴
    .then(resp => resp.json()) //텍스트 유사파일로 만듬
    .then(json1 => { //실제 값 전달
      return fetch(weatherURL) // url 정보가져옴
        .then(resp => resp.json())//텍스트 유사파일로 만듬
        .then(json2 => { //실제 값 전달
          return {
            news: json1.data, 
            weather: json2
          }
        });
    })
}
function getNewsAndWeatherAll() {
  return Promise.all([ //배열형태로 2개 promise를 받음
    fetch(newsURL), 
    fetch(weatherURL)
  ])
    .then(([newsResponse, weatherResponse]) => { //순서대로 데이터값 가짐
      return Promise.all([newsResponse.json(), weatherResponse.json()])// 텍스트 유사파일로 만듬
    })
    .then(([json1, json2]) => {
      return {
        news: json1.data,
        weather: json2
      }
    })
}
async function getNewsAndWeatherAsync() { //함수명 앞에 async 입력

  let json1 = await fetch(newsURL).then(resp => resp.json()); //await 사용으로 처리되기가지 임시 대기한다.
  let json2 = await fetch(weatherURL).then(resp => resp.json());

  return { //반환
    news: json1.data,
    weather: json2
  }
}

정리글 참조
출처 : https://velog.io/@khy226/%EB%8F%99%EA%B8%B0-%EB%B9%84%EB%8F%99%EA%B8%B0%EB%9E%80-Promise-asyncawait-%EA%B0%9C%EB%85%90

profile
매일 뭐든하기

0개의 댓글