首页  >  文章  >  web前端  >  带 Fetch 的 AbortController

带 Fetch 的 AbortController

王林
王林原创
2024-09-12 10:31:06804浏览

AbortController with Fetch

JavaScript 中的 AbortController 是一个实用程序,用于取消或中止异步操作,例如获取请求或事件侦听器等其他任务,这些任务可能需要一些时间才能完成。它允许您停止不再需要的操作,这对于提高性能和管理资源很有用。

示例用例:

// Create an AbortController instance
const controller = new AbortController();
const signal = controller.signal;

// Start a fetch request with the signal attached
fetch('https://api.example.com/data', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch request was aborted');
    } else {
      console.error('Fetch error:', err);
    }
  });

// If we need to cancel the request:
controller.abort(); // This will abort the fetch request

  1. 控制器:AbortController 创建一个管理中止过程的控制器。

  2. Signal:AbortController 有一个信号属性,您可以将其传递给 fetch() 等函数。该信号用于在操作应中止时进行通信。

  3. abort() 方法:当调用 abort() 方法时,会触发信号并取消操作。

以上是带 Fetch 的 AbortController的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn