【问题标题】:Timeout fetch -React Native超时提取 -React Native
【发布时间】:2018-06-11 21:56:40
【问题描述】:

我正在使用 fetch API 访问休息服务器。如果服务器宕机,我需要设置 30 秒的超时并显示类似“发生超时”的警报。

我的 Fetch 调用

 fetch('url', {
            method: "POST",
            headers: {

                'Accept': '*/*',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(objReq)
        })
            .then(response => response.text())
            .then(responseJson => {
                if (responseJson != null && responseJson != undefined) {
            })
            .catch(error => {
                alert(error + " from error")
                console.error(error);
            });

我无法正确设置超时。是否有一种简化的方法来实现超时。关于在调用 API 之前检查互联网连接的任何建议。

【问题讨论】:

标签: javascript reactjs react-native ecmascript-6 promise


【解决方案1】:

引用的答案是要走的路,但可能要清理以使用部分应用程序(关闭):

const withTimeout = time => promise =>
  Promise.race(
    [
      promise,
      new Promise(
        (resolve,reject)=>
          setTimeout(
            _=>reject("Timeout happened")
            ,time
          )
      )
    ]
  );
const in30Seconds = withTimeout(30000);

in30Seconds(
  fetch('url', {
    method: "POST",
    headers: {
        // 'x-nanobnk-auth': this.token,
        'Accept': '*/*',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(objReq)
  })
)
  .then(response => response.text())
  .then(responseJson => {
      if (responseJson != null && responseJson != undefined) {

      }
  })
  .catch(error => {
      alert(error + " from error")
      console.error(error);
  });

【讨论】:

  • 这是否也关闭了 Fetch 连接?
  • @KartiikeyaBaleneni 不,它没有,但如果你能告诉我如何cancel a fetch request 我可以为你添加它。当它超时时,它不会在 fetch 最终完成时解析,因为 promise 只能解析或拒绝一次。
猜你喜欢
  • 2018-06-09
  • 2017-11-23
  • 1970-01-01
  • 2019-07-03
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
相关资源
最近更新 更多