反应原生 fetch 不调用 then 或 catch

2022-01-20 00:00:00 fetch javascript react-native

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

I am using fetch to make some API calls in react-native, sometimes randomly the fetch does not fire requests to server and my then or except blocks are not called. This happens randomly, I think there might be a race condition or something similar. After failing requests once like this, the requests to same API never get fired till I reload the app. Any ideas how to trace reason behind this. The code I used is below.

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

推荐答案

Fetch 可能会抛出错误,而您尚未添加 catch 块.试试这个:

Fetch might be throwing an error and you have not added the catch block. Try this:

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 */});

请记住,Promise 通常具有这种格式:

Remember that Promises usually have this format:

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 */ });

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

I'm using it in this way because I faced the same problem before.

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

Let me know if it helps to you.

相关文章