기본적인 가져오기 요청은
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
이렇게 이루어 집니다.
여기서는 네트워크를 통해 JSON 파일을 가져 와서 콘솔에 인쇄합니다.
fetch()은 하나의 인수 (가져올 리소스에 대한 경로)를 취하고 응답 ( Response객체)을 포함하는 promise를 반환합니다 .
예제를 통해 더 알아봅시다.
2새의 url에서 객체에 담을 정보를 가져와서 객체를 리턴해 봅시다.
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
function getNewsAndWeather() {
let obj = {};
return fetch(newsURL)
.then(response => response.json())
.then(data => {
obj['news'] = data.data;
return fetch(weatherURL);
})
.then((response)=> response.json())
.then(data => {
obj['weather'] = data;
return obj;
})
}
결과로
const obj = {
news: [
{
row_id: 2,
title: '2021년 경제 성장률 전망 밝아',
source: 'A신문',
timestamp: '2020/12/30',
},
{
row_id: 3,
title: '코로나19 증가추세 대폭 하락해',
source: 'BBC',
timestamp: '2020/12/29',
},
{
row_id: 4,
title: '코드스테이츠 취업연계 파트너사 xxx건 돌파',
source: '스타트업 뉴스',
timestamp: '2020/12/31',
},
],
weather: { status: 'sunny', tempature: '28', finedust: 'good' },
};
이 obj에 담겼다.
위의 소스를 Promise.all로 표현하면
function getNewsAndWeatherAll() {
return Promise.all([
fetch(newsURL).then(response => response.json()),
fetch(weatherURL).then(response => response.json())
])
.then((data) =>{
return {news: data[0].data, weather : data[1]};
})
}
async/await로 포현하면
async function getNewsAndWeatherAsync() {
// TODO: async/await 키워드를 이용해 작성합니다
let news = await fetch(newsURL).then(response => response.json())
let weather = await fetch(weatherURL).then(response => response.json())
return {news: news.data, weather : weather};
}