反应本机获取不调用然后或捕获

Bar*_*zel 8 javascript fetch react-native

我正在使用fetch在react-native中进行一些API调用,有时随机fetch不会向服务器发送请求,而我的then或except块也不会被调用.这是随机发生的,我认为可能存在竞争条件或类似情况.在这样的请求失败后,对同一API的请求永远不会被解雇,直到我重新加载应用程序.任何想法如何追踪这背后的原因.我使用的代码如下.

const host = liveBaseHost;
const url = `${host}${route}?observer_id=${user._id}`;
let options = Object.assign({
        method: verb
    }, params
    ? {
        body: JSON.stringify(params)
    }
    : null);
options.headers = NimbusApi.headers(user)
return fetch(url, options).then(resp => {
    let json = resp.json();
    if (resp.ok) {
        return json
    }
    return json.then(err => {
        throw err
    });
}).then(json => json);
Run Code Online (Sandbox Code Playgroud)

Fac*_*cca 7

Fetch可能会抛出错误而您没有添加catch块.试试这个:

return fetch(url, options)
  .then((resp) => {
    if (resp.ok) {
      return resp.json()
        .then((responseData) => {
          return responseData;
        });
    }
    return resp.json()
      .then((error) => {
        return Promise.reject(error);
      });
  })
  .catch(err => {/* catch the error here */});
Run Code Online (Sandbox Code Playgroud)

请记住,Promises通常具有以下格式:

promise(params)
  .then(resp => { /* This callback is called is promise is resolved */ },
        cause => {/* This callback is called if primise is rejected */})
  .catch(error => { /* This callback is called if an unmanaged error is thrown */ });
Run Code Online (Sandbox Code Playgroud)

我是以这种方式使用它,因为我之前遇到过同样的问题.

如果它对您有帮助,请告诉我.