API를 통해 데이터를 받아 뿌리기
날씨관련 API OpenWeatherAPI에서 각 도시별 날씨정보를 받아와 HTML에 적용하는 과정을 해보았다.
한번의 렌더링에서 두번의 패치가 있어야 해서 fetch()를 두 번 진행했다.
fetch()를 통해서 API 요청을 할 수 있다.function getData() {
fetch(API_URL)
.then(function (res) {
return res.json();
});
.then(function (json) {
console.log(json);
});
};
1) fetch에 인자로 내가 요청을 보낼 API Endpoint를 넣어준다.
2) then을 통해 response를 가져와 response에 담겨있는 json데이터를 꺼낸다.
3) then을 통해 콜백에 json에 꺼낸 JSON데이터를 넣는다.
Throw new Error('messege')를 통해서 에러를 보낼 수 있다.function getData() {
fetch(API_URL)
.then(function (res) {
if(res.status === 200 || res.ok) return res.json();
throw new Error('messege');
});
.then(function (json) {
console.log(json)
});
.cathc(function (err) {
console.error(errr)
});
};
1) 정상적인 응답이 아닌경우 ok, status를 통해 판별하여 status === 200 || ok === true에만 json을 반환하도록 한다.
2) 아닌경우 throw new Error('messege')를 생성 강제로 에러가 발생한 것을 넘겨준다.
async & await을 통해 결과에 따라 렌더링을 하도록 설정한다.const getData = (el) => {
return fetch(API_URL)
.then(function (res) {
if(res.status === 200 || res.ok) return res.json();
throw new Error('messege');
});
.then(function (json) {
console.log(json, el)
});
.cathc(function (err) {
console.error(errr)
});
};
// getData()의 반환값은 Promise형태로 그 결과가 비동기적으로 처리된다.
async function print() {
const arr = [1,2,3,4]
const mapping = arr.map(el => getdata(el))
// arr [Promise,Promise,Promise,Promise]
await Promise.all(mapping)
return console.log("done")
}
print()
// json, 1
// json, 2
// json, 3
// json, 4
// json, 5
// done
async와 await없이 맵핑에 비동기처리가 있게 되면 정상적인 출력 결과를 얻지 못한다.
(done이 먼저 출력됨) 때문에 Promise.all을 통해서 해당 데이터의 처리가 끝나는 것을 받아낼 수 있게 하고,
await을 통해 끝나고 나서의 결과가 있으면 다음 실행으로 이어가게 해줄 수 있다.