(Vue JS) 我很难在这些承诺中插入 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;
});
}
只需将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
});
如果您坚持使用 if
而不是 Promise API 来控制流,那么您可以有条件地从 then
内部返回另一个 promise 链。如果 200 以外的任何内容,以下内容将返回res.status
并且不执行任何操作:
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;
}