使用【AbortController】终止请求

AbortController 是一个 Web API,用于终止一个或多个 Web 请求。当你使用 fetch API 发送异步请求时,你可能需要在某些情况下主动终止这些请求。使用 AbortController 可以实现这一功能。

基本用法:

  1. 创建一个 AbortController 实例:

    const controller = new AbortController();
  2. 通过 controller.signal 获取信号,并在 fetch 请求中使用它:

    fetch(url, { signal: controller.signal })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => {
        if (err.name === 'AbortError') {
          console.log('Fetch aborted');
        } else {
          console.error('Fetch error:', err);
        }
      });
  3. 终止请求: 当你需要取消 fetch 请求时,可以调用 controller.abort() 方法。

    controller.abort();

        使用 AbortController 可以让你更好地控制资源和提高应用的性能,尤其是在处理需要长时间等待的请求或者在组件卸载时取消未完成的请求时非常有用。

        笔者在react中取消请求,遇到了此问题,记录一下,共勉!

相关推荐

  1. 使用AbortController终止请求

    2024-06-10 12:10:05       9 阅读
  2. s AbortController 接口取消多次请求 取消上次请求

    2024-06-10 12:10:05       12 阅读
  3. 知识点:AbortController是什么

    2024-06-10 12:10:05       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-10 12:10:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-10 12:10:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-10 12:10:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-10 12:10:05       20 阅读

热门阅读

  1. 设计模式之工厂模式

    2024-06-10 12:10:05       10 阅读
  2. 百度之星2022题目记录

    2024-06-10 12:10:05       9 阅读
  3. UE5实战篇二(对话系统1):导语

    2024-06-10 12:10:05       11 阅读
  4. oj数据库名字总结

    2024-06-10 12:10:05       10 阅读
  5. Python高级编程:数据分析与数据可视化

    2024-06-10 12:10:05       12 阅读
  6. 轻量化微调使用场景对比

    2024-06-10 12:10:05       7 阅读
  7. web前端大数据:挑战、机遇与未来发展

    2024-06-10 12:10:05       10 阅读
  8. 中国飞行器设计创新大赛多旋翼无人机任务飞行

    2024-06-10 12:10:05       12 阅读
  9. 双系统 Ubuntu无静态IP

    2024-06-10 12:10:05       10 阅读
  10. Flutter教育学习类APP常用的第三方库总汇

    2024-06-10 12:10:05       12 阅读