fetch API

김범주·2022년 3월 11일
0

Code Review

목록 보기
6/15

basicChaining.js

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

function getNewsAndWeather() {
  // TODO: fetch을 이용해 작성합니다
  // TODO: 여러개의 Promise를 then으로 연결하여 작성합니다 
  let obj = {}
  return fetch(newsURL)
  .then((res) => res.json())
  .then((news) => {
    obj.news = news.data
    return fetch(weatherURL)
  })
  .then(res => res.json())
  .then(weather => {
    obj.weather = weather
    return obj
  })
}

promiseAll.js

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

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  // 1. 따로 변수를 선언해주고 거기에 fetch를 통해서 response에 promise 객체를 받아온다
  // 2. 객체를 json으로 변환해준다
  // 3. Promise.all() 안에 선언한 변수 넣어준다

  let news = fetch(newsURL)
  .then(res => res.json())
  let weather = fetch(weatherURL)
  .then(res => res.json())

  let ans = {}
  return Promise.all([news, weather])
  .then(res => {
    ans.news = res[0].data
    ans.weather = res[1]
    return ans
  })
}

asyncAwait.js

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

async function getNewsAndWeatherAsync() {
  // TODO: async/await 키워드를 이용해 작성합니다
  let news = await fetch(newsURL)
  .then(res => res.json())
  let weather = await fetch(weatherURL)
  .then(res => res.json())

  let ans = {}
  ans.news = news.data
  ans.weather = weather
  return ans
}
profile
개발꿈나무

0개의 댓글