(Vue JS) I'm having difficulties inserting an if statement within these promises. I'd like to us an 'if (res.status===200)' right after receiving the response. How can I break this up a little? I'm getting errors every time I try.
fetchFeatured() {
console.log("fetching featured video");
fetch(
`${this.url}?part=${this.part}&maxResults=${
this.maxResults
}&playlistId=${this.playlistId}&key=${this.key}`
)
.then(res => res.json())
.then(json => {
console.log(json.items);
this.videos = json.items;
});
}
Just put the if
check into the first .then
. If the status is not 200, you can throw an error to break out of the .then
chain early (though calling .json()
on the bad response would also throw an error):
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;
});
}
Make sure to return
the fetch
Promise chain. Then, calls of fetchFeatured
can handle errors by putting a .catch
onto the end, for example
this.fetchFeatured()
.catch((err) => {
console.log('Bad response:', err);
// populate error element with error message
});
If you're insisting on controlling the flow with if
, as opposed to with the Promise API, then you can conditionally return another promise chain from inside then
. The following will return and not do anything if res.status
is anything other than 200:
fetchFeatured() {
console.log('fetching featured video');
fetch('URL WITH PARAMS HERE')
.then(res => {
// Here's the `if` you're looking for:
if (res.status !== 200) return;
// Return a promise chain from inside our promise chain!
return res.json().then(json => {
console.log(json.items);
this.videos = json.items;
});
});
}
The previous paradigm leads to indentation hell - in general you'll be much happier working with async
+ await
:
async fetchFeatured() {
let res = await fetch('URL WITH PARAMS HERE');
if (res.status !== 200) return;
let json = await res.json();
console.log(json.items);
this.videos = json.items;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.