Просто поместите чек if
в первый .then
.Если статус не равен 200, вы можете выдать ошибку, чтобы вырваться из цепочки .then
раньше (хотя при вызове .json()
в случае неправильного ответа также выдается ошибка):
fetchFeatured() {
console.log("fetching featured video");
const url = `${this.url}?part=${this.part}&maxResults=${
this.maxResults
}&playlistId=${this.playlistId}&key=${this.key}`;
return fetch(url)
.then(res => {
if (res.status===200) {
return res.json();
} else {
throw new Error('Status was not 200!');
}
})
.then(json => {
console.log(json.items);
this.videos = json.items;
});
}
Убедитесь, чтоreturn
Цепочка обещаний fetch
.Затем вызовы fetchFeatured
могут обрабатывать ошибки, помещая .catch
в конец, например
this.fetchFeatured()
.catch((err) => {
console.log('Bad response:', err);
// populate error element with error message
});