p r o g r a m m i n g
Fetch API 과제 리뷰 (promise chaining, promise.all, async&await)
hee.hee
2022. 6. 5. 20:01
fetch와 json 메서드, Response 객체
fetch 함수는 HTTP 응답을 나타내는 Response 객체를 래핑한 프로미스를 반환하므로 후속 처리 메서드 then을 통해 프로미스가 resolve한 response 객체를 전달받을 수 있다. Response 객체는 HTTP 응답을 나타내는 다양한 프로퍼티를 제공한다.
예를 들어 fetch 함수가 반환한 프로미스가 래핑하고 있는 MIME 타입이 application.json인 HTTP 응답 몸체를 취하려면 Response.prototype.json 메서드를 사용한다. Response.prototype.json 메서드는 Response 객체에서 HTTP 응답몸체를 취득하여 역직렬화 한다. (js에서 읽을 수 있는 데이터로 변환시켜줌)
part3-1 getNewsAndWeather
- 체이닝의 결과가 Promise 형태로 리턴되어야 합니다‣
- /data/latest 의 응답 내용과 /data/weather 응답 내용을 합쳐 새로운 객체로 리턴되어야 합니다‣
- fetch를 활용하세요. 총 두 번 사용해야 합니다‣
- Promise.all 또는 async/await을 사용하지 않고 풀어보세요
const newsURL = "http://localhost:4999/data/latestNews";
const weatherURL = "http://localhost:4999/data/weather";
function getNewsAndWeather() {
// TODO: fetch을 이용해 작성합니다
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
let obj = {}; // 빈객체
return fetch(newsURL) // return fetch에 url 넣어줌
.then((response) => response.json()) // fetch의 결과(promise) response를 json 메서드로 body 역직렬화 (js객체가 됨)
.then((data) => { // 위의 then에서 리턴한 프로미스(data)를 then의 인자로 전달한다
obj["news"] = data.data; // 빈 객체의 'news'키에 response의 body중, data를 할당한다
return fetch(weatherURL); // weatherURL을 이어서 구하기 위해 리턴한다.
})
.then((response) => response.json()) fetch가 리턴한 프로미스 response를 json 한다
.then((data) => { // response 데이터로 then의 콜백함수 호출
obj["weather"] = data; // 객체의 weather 키에 data 할당(weather는 문자열이어서 그대로 할당해주면 된다)
return obj;
});
}
Promise.all
part3-2 getNewsAndWeatherAll
- Promise 형태로 리턴되어야 합니다
- Promise.all을 사용해서 풀어야 합니다
- /data/latest 의 응답 내용과 /data/weather 응답 내용을 합쳐 새로운 객체로 리턴되어야 합니다
const newsURL2 = "http://localhost:4999/data/latestNews";
const weatherURL2 = "http://localhost:4999/data/weather";
function getNewsAndWeatherAll() {
// TODO: Promise.all을 이용해 작성합니다
let obj = {};
const news = fetch(newsURL2).then((response) => response.json());
const weather = fetch(weatherURL2).then((response) => response.json());
//이전 문제와 똑같이 fetch 해주고 각각 변수에 할당한다
return Promise.all([news, weather]).then((res) => { //Promise.all로 배열에 합쳐 담아준다
//response의 data는 지금 [{news}, "weather"] 이 상태
obj.news = res[0].data; //news 키에 news의 data를 담아줌
obj.weather = res[1]; //weather키에 weather를 담아줌
return obj; // 담아준 obj 리턴
});
}
async&await
await 키워드는 반드시 프로미스 앞에서 사용해야 한다. await 키워드는 프로미스가 settled인 상태(비동기 처리가 수행된 상태)까지 기다렸다가 settled 상태가 되면 프로미스가 resolve한 처리 결과를 반환한다. 그 결과는 news와 weather 변수에 할당된다.
await는 다음 실행을 일시중지 시켰다가 프로미스가 settled 상태가 되면 다시 재개한다.
part3-3 async&await
- async 키워드를 사용한 함수는 AsyncFunction의 인스턴스입니다‣
- /data/latest 의 응답 내용과 /data/weather 응답 내용을 합쳐 새로운 객체로 리턴되어야 합니다.
- async/await를 활용하세요. 총 두번 사용해야 합니다.
const newsURL3 = "http://localhost:4999/data/latestNews";
const weatherURL3 = "http://localhost:4999/data/weather";
async function getNewsAndWeatherAsync() { // 함수 앞에 async 키워드를 썼다
const news = await fetch(newsURL3).then((response) => response.json()); // await 키워드로 동기처럼 쓸 수 있음
const weather = await fetch(weatherURL3).then((response) => response.json());
return { news: news.data, weather: weather };
}