超时提取-React Native

问题描述 投票:0回答:1

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

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

javascript reactjs react-native ecmascript-6 promise
1个回答
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);
  });
© www.soinside.com 2019 - 2024. All rights reserved.