if (response.status !== 200) {
console.warn(
"Looks like there was a problem. Status Code: " + response.status
);
return;
}
In case there is an error from the API then the site is broken, the user would have nothing todo. so first we need to handle these errors from the .catch so instead of return; we would need throw new Error(response.status); (this was taken from this workshop).
speaking of the .catch this takes us to the next problem
In case the code reaches the .catch then the user will see nothing, he has no indication that an error has happened.
3) the response.json().then(function (data) {, it's cleaner to have the .then one after the other instead of inside each other.
Like this for example is cleaner
fetch(`https://pokeapi.co/api/v2/pokemon/${name}`)
.then(response => {
if (!response.ok) throw new Error(response.status);
return response.json();
})
// if we get a successful response
.then(pokemonData => {
A reason for using promises is to avoid callback hell, and if you have .then inside a .then then you creating callback hell structure but with promises 😆
There are a couple of issues with this fetch:
1) The following code:
In case there is an error from the API then the site is broken, the user would have nothing todo. so first we need to handle these errors from the
.catch
so instead ofreturn;
we would needthrow new Error(response.status);
(this was taken from this workshop).speaking of the
.catch
this takes us to the next problem2) The following code:
In case the code reaches the
.catch
then the user will see nothing, he has no indication that an error has happened.3) the
response.json().then(function (data) {
, it's cleaner to have the.then
one after the other instead of inside each other.Like this for example is cleaner
A reason for using promises is to avoid callback hell, and if you have
.then
inside a.then
then you creating callback hell structure but with promises 😆