(Vue JS)我很难在这些promise中插入if语句。收到回复后,我想给我们一个'if(res.status === 200)。我该如何分解?每次尝试时都会出错。
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;
});
}
答案 0 :(得分:0)
只需将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
Promise链。然后,fetchFeatured
的调用可以通过将.catch
放在末尾来处理错误,例如
this.fetchFeatured()
.catch((err) => {
console.log('Bad response:', err);
// populate error element with error message
});
答案 1 :(得分:0)
如果您坚持使用if
来控制流程,而不是Promise API,那么您可以有条件地从then
内部返回另一个Promise链。如果res.status
不是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;
});
});
}
以前的范式导致缩进地狱-通常,使用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;
}