- basicChaining.js
const newsURL = 'http://localhost:4999/data/latestNews'; // 객체 안의 data 의 속성 값
const weatherURL = 'http://localhost:4999/data/weather'; // 단일 객체로 되어있음
function getNewsAndWeather() {
return fetch(newsURL) // 응답 객체 형태
.then((response) => response.json()) // .json 을 활용하여 json형태로 변환시킨 후
.then((json1) => { // Promise로 전달한다
return fetch(weatherURL)
.then((response) => response.json())
.then((json2) => {
return {
news: json1.data,
weather: json2,
};
});
});
}
// 두개의 결과를 하나의 객체로 합치는게 목표
readAllUsersChaining();
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeather
}
}
- PromiseAll.js
여기서부터 의문이 든다. 어떻게 URL을 작성하지도 않는데 값을 가져올 수 있지..?
function getNewsAndWeatherAll() {
return Promise.all([fetch(newsURL), fetch(weatherURL)]) // Promise.all()에서 전달인자는 순회 가능한 객체가 들어감
.then(([newsResponse, weatherResponse]) => {
return Promise.all([newsResponse.json(), weatherResponse.json()]);
})
.then(([json1, json2]) => { // .json 을 활용하여 json형태로 변환시킨 후
return {
news: json1.data, // 키 값을 리턴
weather: json2, // 객체 리턴
};
});
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAll
}
}
- asyncAwait.js
async function getNewsAndWeatherAsync() {
// TODO: async/await 키워드를 이용해 작성합니다
let result1 = await fetch(newsURL).then(response => response.json()); // 각각 json의 형태로 전환해주고 변수에 저장
let result2 = await fetch(weatherURL).then(response => response.json());
return { // async/await은 전달값을 꺼내주니까 바로 리턴
news: result1.data,
weather: result2
}
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAsync
}
}