<FETCH API>
- a newer way of making request wia JS
- supports promise
fetch('https://swapi.co/api/planets/')//promise
.then((response) => {//get promise, need then
if (!response.ok) { //2. so we need to check response here
console.log('Somthing Wrong!');
console.log(response.status);
}
return response.json(); //아래의 데이터로 리턴
})
.then((data) => {//get another promise, need another then
console.log('Fetched all Planets');
const filmURL = data.results[0].films[0];//첫플레닛 배열의 첫 필름 배열
return fetch(filmURL)//promise
})
.then((response) => {
if (!response.ok) {
console.log('Somthing Wrong!');
console.log(response.status);
}
return response.json(); //아래의 데이터로 리턴
})
.then(data => {
console.log('Fetched First Film, based on first planet');
console.log(data.title);//첫필름배열의 타이틀 출력
})
.catch((err) => { // 1. if we put wrong address, this catch is not gonna runned(becoz we still get a response from API), unless sever is completley rejected the request(ex;200, internet shutdown or not ok).
//->it is how fetch runned
console.log('Somthing Wrong!');
console.log(err);
});
- Refactoring
const checkStatusAndParse = (response) => {
if (!response.ok) {
console.log('Somthing Wrong!');
console.log(response.status);
}
return response.json();
};
const printPlanets = (data) => {
console.log('Loaded 10 Planets');
for (let planet of data.results) {
console.log(planet.name);
}
return Promise.resolve(data.next);
};
const fetchNextPlanets = (url = 'https://swapi.co/api/planets/') => {
return fetch(url);
};
fetchNextPlanets()//원하는 만큼 복사가능
.then(checkStatusAndParse)
.then(printPlanets)
.then(fetchNextPlanets)
.then(checkStatusAndParse)
.then(printPlanets)
.then(fetchNextPlanets)
.then(checkStatusAndParse)
.then(printPlanets)
.catch((err) => {
console.log('Somthing Wrong!');
console.log(err);
});
'javascript' 카테고리의 다른 글
JavaScript/ The Async & The Await (0) | 2020.04.15 |
---|---|
JavaScript/ AXIOS (0) | 2020.04.14 |
JavaScript/ AJAX & XML Http Request (0) | 2020.04.14 |
JavaScript/ CallBack Hell & Promise! (0) | 2020.04.14 |
JavaScript/ Extends, Super and SubClasses! (0) | 2020.04.14 |