反应本机提取不调用然后捕获 [英] react native fetch not calling then or catch

查看:60
本文介绍了反应本机提取不调用然后捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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);

推荐答案

抓取可能会引发错误,并且您尚未添加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.

这篇关于反应本机提取不调用然后捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆