Fetch api

»

fetch API

네트워크를 통해 이뤄지는 요청 중 가장 흔한 경우는 바로 URL로 요청하는 경우입니다

이렇게 URL로 요청하는 걸 가능하게 해주는 API가 바로 fetch API입니다

fetch API 는 Promise의 형식으로 되있습니다

const url = 'https://대충링크내용이라는뜻.com';

fetch(url)
  .then((response) => response.json()) // 자체적으로 json() 메소드가 있어, 응답을 JSON 형태로 변환시켜서 다음 Promise로 전달합니다
  .then((json) => console.log(json)) // 콘솔에 json을 출력합니다
  .catch((error) => console.log(error)); // 에러가 발생한 경우, 에러를 띄웁니다

fetch 사용법

fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));

// 예시
// Promise.all
function getNewsAndWeatherAll() {
  let news = fetch(newsURL)
    .then(response => response.json());
  let weather = fetch(weatherURL)
    .then(response => response.json());
  return Promise.all([news, weather])
    .then(values => {
      return {
        news: values[0].data,
        weather: values[1]
      };
    })
}

// async await
async function getNewsAndWeatherAsync() {
  let json1 = await fetch(newsURL)
    .then(response => response.json());
  let json2 = await fetch(weatherURL)
    .then(response => response.json());

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