然后在捕获后仍被调用甚至被捕获

时间:2019-07-05 10:16:19

标签: javascript promise fetch

我想将获取承诺返回给上层使用,但是我发现即使这个获取承诺失败(被捕获),上层的仍然被调用。仅当获取成功时才可能调用“上一层的”吗?

export default function request(url, options) {
  .......
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      // debugPrint("receive response" + JSON.stringify(data));

      if (+data.status.code !== 200) {
        message.error(data.status.message || "please retry");
      }
      return data;
    })
    .catch(err => {
      message.error(err.toString() || "please retry");
      return err;
    });
}

// then I call request this way:
export function userLogin(account) {
  return request(`${domain}/signin/get_accesstoken`, {
    method: "POST"
  }).then(data => {
    // even catch be called, this then still be called. Is it possible only call this then when catch not be called ?

    do something;
    return data;
  });
}

第二次修改: 我试图在那时返回一个诺言,但看起来它不是一个诺言,我不知道为什么。

export default function request(url, options) {
  .......
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      // debugPrint("receive response" + JSON.stringify(data));

      if (+data.status.code !== 200) {
        message.error(data.status.message || "please retry");
      }
      return new Promise(resolve=>{
          resolve(data)
      });
    })
    .catch(err => {
      message.error(err.toString() || "please retry");
      return new Promise((resolve, reject)=>{
         reject(err)
      });
    });
}

编辑第三个:

    export default function request(url, options) {
  .......
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      // debugPrint("receive response" + JSON.stringify(data));

      if (+data.status.code !== 200) {
        message.error(data.status.message || "please retry");
      }
      return data;
    })
    .catch(err => {
      message.error(err.toString() || "please retry");
      return;
    });
}

    // then I call request this way:
export function userLogin(account) {
  return request(`${domain}/signin/get_accesstoken`, {
    method: "POST"
  }).then(data => {
    // add this
    if (!data) {
      return
     }
    do something;
    return data;
  });
}

1 个答案:

答案 0 :(得分:0)

如果仅在成功的情况下要调用上层的then,则在catch的{​​{1}}块中引发一些错误,而不是返回fetch

err