복습
[S2U3] 비동기 복습
Heemok
2023. 5. 17. 19:54
Fetches 과제 복습
1번과제
fetch메서드를 이용하여 newsURL을 받아서 .then 메서드를 사용하여 parsing하고
그 parsing받은 값으로 다시 fetch메서드를 사용하여 weatherURL을 받아서 패싱하고 리턴하면
news와 weather에 접근이 가능해진다.
const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';
function getNewsAndWeather() {
// TODO: fetch을 이용해 작성합니다
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
return fetch(newsURL) //newsURL을 받아서
.then((response) => response.json()) //parsing 시켜주고
.then((news) => {
// news는 받아온 newsURL
return fetch(weatherURL) //weatherURL을 받아서
.then((response) => response.json())//parsing 시켜주고
.then((weather) => {
// 똑같은 작업 한번 더 진행
return { // 객체안에 모아서 리턴해준다.
// 이 스코프에서만 news, weather 에 접근 가능하다
news : news.data,
weather : weather
};
})
});
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeather
}
}
2번과제
fetch로 url정보를 배열로 받아온 후 Promise.all을 사용하여 한번에 처리를 진행하고 resolve된 값이 되면 전부
parsing처리를 해주어 넘겨주면 그 데이터에 접근이 가능해진다.
function getNewsAndWeatherAll() {
// TODO: Promise.all을 이용해 작성합니다
let fetches = [fetch(newsURL), fetch(weatherURL)]; //fetch로 URL을 받은 것을 배열에 다 모은다.
//여기서 console.log(fetches)를 해보면 [Promise, Promise]라는 결과를 볼 수 있을 것이다.
return Promise.all(fetches).then(fetched => { //Promise.all로 한번에 처리를 해줄 것이다.
//Promise.all을 해주면 resolve된 값이 된다. console.log(fetched)를 해보면 [Response, Response]라는 결과를 볼 수 있다.
const parsed = fetched.map(el => el.json()); //전부 parsing처리를 해준다.
//console.log(parsed) 의 결과로 [Promise, Promise]가 되는 것을 볼 수 있다.
return Promise.all(parsed); //parsing처리된 데이터들을 넘겨줄 것이다. 근데 여기서 Promise.all을 한번더 사용하는 이유는
//json처리를 하면서 다시 Promise가 되었기 때문에(위의 콘솔로그 참고) 다시 resolve된 값으로 바꿔주기위해
//Promise.all을 한번 더 사용해준다.
}).then(parsed => {
const news = parsed[0].data;
const weather = parsed[1];
return {news, weather}
})
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAll
}
}
3번과제
async메서드를 사용하여 await키워드를 이용해 fetch를 사용하여 URL에 접근하고 패싱하여 데이터에 접근한다.
async function getNewsAndWeatherAsync() {
// TODO: async/await 키워드를 이용해 작성합니다
const json1 = await fetch(newsURL).then((value) => value.json());
const json2 = await fetch(weatherURL).then((value) => value.json());
return {news: json1.data, weather: json2}
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAsync
}
}