如何将if语句插入这一系列的promise中? (Vue JS)

时间:2019-01-24 20:43:14

标签: javascript vue.js promise

(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;
    });
 }

2 个答案:

答案 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;
}