언젠간코딩잘함 2023. 3. 21. 21:26

01_basicChaining

function getNewsAndWeather() {
  let fetchNewsWeather = {};
  return fetch(newsURL)
    .then(response => response.json()) // newsURL 데이터를 json으로 변환
    .then(response => {
      fetchNewsWeather.news = response.data; // .data 속성을 .news에 할당
      return fetch(weatherURL);
    })
    .then(response => response.json()) // weatherURL 데이터를 json으로 변환
    .then(response => {
      fetchNewsWeather.weather = response; // .weather에 할당
      return fetchNewsWeather;
    });
}

 

02_promiseAll

function getNewsAndWeatherAll() {
  let news = fetch(newsURL).then(response => response.json());
  let weather = fetch(weatherURL).then(response => response.json());

  return Promise.all([news, weather]) // 배열로 반환
    .then(response => {
      // response[0].data는 news, response[1]은 weather
      return { news: response[0].data, weather: response[1] };
    });
}

 

03_asyncAwait

async function getNewsAndWeatherAsync() { // async
  // await은 resolve될 때까지 실행을 멈추고, resolve될 때까지 기다린 후 결과값을 반환
  const news = await fetch(newsURL).then(response => response.json());
  const weather = await fetch(weatherURL).then(response => response.json());
  return { news: news.data, weather };
}