You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何实现fetch请求超时N秒后终止并跳转页面?

优化建议

  • 修正Promise初始化时机:原代码中fetch请求和计时器在页面加载时就会立即启动,而非调用init()时才同步触发,若存在延迟调用init()的场景会导致计时逻辑完全错位,建议将二者移入init函数内部,保证请求和计时同时启动。
  • 补全fetch异常处理逻辑:fetch默认不会对HTTP错误状态(4xx/5xx)抛出异常,仅网络故障时才会reject,需要主动判断response.ok校验请求是否成功;同时要捕获JSON解析、请求报错等异常场景,避免未处理的rejection导致页面报错。
  • 增加请求中止逻辑:超时跳转后未完成的fetch请求仍会在后台运行,浪费带宽资源,建议使用AbortController在超时时主动中止请求。
  • 替换魔法值判断逻辑:原代码用-1作为超时标识,若接口合法返回值本身为假值(0、空字符串、null等)会触发误判,建议使用明确的结构化标识区分超时和请求成功的状态,避免逻辑冲突。
  • 增加全局异常捕获:补充catch块处理所有未预见的异常,避免静默失败。

优化后代码示例

function init() {
    // 初始化中止控制器
    const controller = new AbortController();
    const signal = controller.signal;

    const fetchData = fetch('https://swapi.devs/api/films', { signal })
        .then(response => {
            // 校验HTTP请求状态
            if (!response.ok) throw new Error(`请求错误:${response.status}`);
            return response.json();
        });

    const timer = new Promise((resolve) => {
        setTimeout(() => {
            // 超时先中止请求
            controller.abort();
            resolve({ isTimeout: true });
        }, 5000);
    });

    Promise.race([fetchData, timer])
        .then(result => {
            if (result.isTimeout) {
                console.log('请求超时,即将跳转');
                window.location.href = "https://www.example.com";
                return;
            }
            // 请求成功处理逻辑
            console.log('请求成功', result);
        })
        .catch(err => {
            // 处理请求报错、中止等异常
            console.error('请求异常', err);
            // 可根据业务需求决定异常时是否跳转
        });
}

init();

内容的提问来源于stack exchange,提问作者tlflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:15:05