首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取API请求超时?

获取API请求超时?
EN

Stack Overflow用户
提问于 2017-10-26 05:23:17
回答 11查看 251.7K关注 0票数 209

我有一个fetch-api POST请求:

代码语言:javascript
复制
fetch(url, {
  method: 'POST',
  body: formData,
  credentials: 'include'
})

我想知道这个的默认超时是什么?我们如何将其设置为3秒或不定秒这样的特定值?

EN

回答 11

Stack Overflow用户

发布于 2018-04-16 12:56:31

更新,因为我原来的答案有点过时,我建议使用中止控制器,如在这里实现的:https://stackoverflow.com/a/57888548/1059828,或者看看这个很好的帖子,用fetch:如何取消HTTP fetch()请求?解释中止控制器

过时的原始答案:

我真的很喜欢这个要旨使用Promise.race的干净方法。

fetchWithTimeout.js

代码语言:javascript
复制
export default function (url, options, timeout = 7000) {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}

main.js

代码语言:javascript
复制
import fetch from './fetchWithTimeout'

// call as usual or with timeout as 3rd argument

fetch('http://google.com', options, 5000) // throw after max 5 seconds timeout error
.then((result) => {
    // handle result
})
.catch((e) => {
    // handle errors and timeout error
})
票数 178
EN

Stack Overflow用户

发布于 2019-09-11 11:52:13

在无止境的优秀回答的基础上,我创建了一个有用的实用函数。

代码语言:javascript
复制
const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
    const controller = new AbortController();
    const promise = fetch(url, { signal: controller.signal, ...options });
    if (signal) signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return promise.finally(() => clearTimeout(timeout));
};
  1. 如果在获取资源之前到达了超时,那么提取将被中止。
  2. 如果在到达超时之前获取资源,则清除超时。
  3. 如果输入信号被中止,那么提取将被中止,超时将被清除。
代码语言:javascript
复制
const controller = new AbortController();

document.querySelector("button.cancel").addEventListener("click", () => controller.abort());

fetchTimeout("example.json", 5000, { signal: controller.signal })
    .then(response => response.json())
    .then(console.log)
    .catch(error => {
        if (error.name === "AbortError") {
            // fetch aborted either due to timeout or due to user clicking the cancel button
        } else {
            // network error or json parsing error
        }
    });

希望这能有所帮助。

票数 70
EN

Stack Overflow用户

发布于 2017-10-26 05:39:27

在fetch API中还没有超时支持。但这可以通过把它包裹在一个承诺中来实现。

就像。

代码语言:javascript
复制
  function fetchWrapper(url, options, timeout) {
    return new Promise((resolve, reject) => {
      fetch(url, options).then(resolve, reject);

      if (timeout) {
        const e = new Error("Connection timed out");
        setTimeout(reject, timeout, e);
      }
    });
  }
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46946380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档