如何使用React js在Fetch API中设置超时

时间:2019-03-10 10:22:15

标签: reactjs

我在react js中使用fetch post方法,并且在向后端发送请求时,它需要7分钟的时间来提供响应,并且在该前端自动超时之前。您能帮我解决一下如何在前端的获取方法中设置10分钟的时间来等待响应,并且仅在后端花费超过10分钟的时间时才超时。 请让我们知道我是否必须安装任何依赖项。

也只是为了通知您,我已经安装了依赖项“ whatwg-fetch-timeout”:“ ^ 2.0.2-timeout”,并且在开发服务器上运行良好 但是,当尝试创建构建包时,它无法创建构建。 示例代码:

fetch("http://" + hostName + ":" + port + "/searchData", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Login: login,
    ID: id
  },
  body: JSON.stringify({
    StartDate: StartDate === "" ? null : StartDate,
    EndDate: EndDate === "" ? null : EndDate,
    FileName: FileName === "" ? null : FileName,
    RecordCount: RecordCount === "" ? null : RecordCount,
    Status: Status
  })
})
  .then(response => {
    resStatus = response.status;
    return response.json();
  })
  .then(responseJson => {
    //source code
  })
  .catch(error => {});

3 个答案:

答案 0 :(得分:0)

如何添加自己的超时时间 像

function timeoutPromise(ms, promise) {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      reject(new Error("promise timeout"))
    }, ms);
    promise.then(
      (res) => {
        clearTimeout(timeoutId);
        resolve(res);
      },
      (err) => {
        clearTimeout(timeoutId);
        reject(err);
      }
    );
  })
}

然后以ES7异步/等待语法调用它

async request() {
  try { 
    let res = await timeoutPromise(10*60*1000, fetch('/hello'));
  } catch(error) {
    // might be a timeout error
  }
}

对于推荐人Fetch API request timeout?,也请尝试此操作。

答案 1 :(得分:0)

如果您可以控制服务器,请考虑在请求和最终响应之间发送状态代码102(仍在处理中),以使客户端知道不超时。

答案 2 :(得分:0)

Promise.race 可以解决这个问题。

// "wait" function returns a new Promise that rejects after waiting
const wait = milliseconds => new Promise(
  (res, rej) => setTimeout(
    () => rej(new Error(`timed out after ${milliseconds} ms`)),
    milliseconds
  )
);

// the fetch could remain unchanged
// ...but it helps to add the "signal" property to abort the request early
const abortController = new AbortController();
const fetchData = fetch(
  'http://url',
  {
    method:"POST",
    signal: abortController.signal
  }
);

// now the fetch races against the wait Promise
const fetchOrTimeout = Promise.race([fetchData, wait(10 * 60 * 1000)]);

// ...and the difference here is that now the logic could have a rejected Error from "wait"
// (also this is the place to send the abort signal to fetch)
fetchOrTimeout
.then(response => { console.log('fetch worked!'); return response.json(); })
.catch(error => { console.log(`fetch error: ${error}`); abortController.abort(); });