//01_basicChaining
const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';
function getNewsAndWeather() {
// 빈 객체 생성
const obj = {};
// 뉴스 데이터 가져오는 fetch
return fetch(newsURL)
.then((response) => response.json()) // 응답을 JSON 형식으로 변환
.then(json1 => {
// 날씨 데이터 가져오는 fetch
return fetch(weatherURL)
.then((response) => response.json()) // 응답을 JSON 형식으로 변환
.then(json2 => {
// 뉴스 데이터를 obj.news에 할당
obj.news = json1.data;
// 날씨 데이터를 obj.weather에 할당
obj.weather = json2;
// 완성된 객체를 반환
return obj;
});
});
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeather
}
}
//02_promiseAll
function getNewsAndWeatherAll() {
// 빈 객체 생성
let obj = {};
// 최신 뉴스 데이터를 가져오는 프로미스 생성
const latestNewsPromise = fetch('http://localhost:4999/data/latestNews')
.then(response => response.json())
// 날씨 데이터를 가져오는 프로미스 생성
const weatherPromise = fetch('http://localhost:4999/data/weather')
.then(response => response.json());
// Promise.all을 사용하여 두 프로미스를 병렬로 처리
return Promise.all([latestNewsPromise, weatherPromise])
.then((x) => {
// 첫 번째 프로미스의 데이터를 obj.news에 할당
obj.news = x[0].data;
// 두 번째 프로미스의 데이터를 obj.weather에 할당
obj.weather = x[1];
// 완성된 객체를 반환
return obj;
});
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAll
}
}
//03_asyncAwait
async function getNewsAndWeatherAsync() {
// 빈 객체 생성
const obj = {};
// 최신 뉴스 데이터를 가져오는 비동기 함수
let a = await fetch('http://localhost:4999/data/latestNews')
.then(response => response.json());
// 날씨 데이터를 가져오는 비동기 함수
let b = await fetch('http://localhost:4999/data/weather')
.then(response => response.json());
// 뉴스 데이터를 obj.news에 할당
obj.news = a.data;
// 날씨 데이터를 obj.weather에 할당
obj.weather = b;
// 완성된 객체를 반환
return obj;
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAsync
}
}