简体   繁体   English

如何在同一个按钮上使用 AbortController 中止获取 HTTP 请求

[英]How to abort fetching HTTP request using AbortController on the same button

The problem is that I need to get only last API response by clicking a "Fetch Data" button.问题是我只需要通过单击“获取数据”按钮来获得最后一个 API 响应。 Earlier requests should be canceled.应取消较早的请求。

The idea is to use AbrotController.这个想法是使用 AbrotController。 Unfortunately, I have a problem, because the requests are not canceled and a console receives the message:不幸的是,我遇到了一个问题,因为请求没有被取消并且控制台收到了消息:

Fetch 1 error: Failed to execute 'fetch' on 'Window': The user aborted a request.获取 1 错误:无法在“窗口”上执行“获取”:用户中止了请求。

Sample code below:下面的示例代码:

<button id="test">Fetch data</button>

let isLoading = false;

let controller = new AbortController();
const abort = () => controller.abort();

const button = document.getElementById("test");

const fetchData = () => {
  controller = new AbortController();
  
  if (isLoading) {
    abort();
  }
  
  isLoading = true;
  
  return fetch('https://jsonplaceholder.typicode.com/todos', {
        signal: controller.signal
      })
      .catch(e => {
        console.warn(`Fetch 1 error: ${e.message}`);
      })
      .finally(() => isLoading = false);;
}

button.addEventListener('click', () => {
  fetchData();
});

It is because you call the controller.abort() on different instance than you initialized signal.这是因为您在与初始化信号不同的实例上调用 controller.abort()。

What about something like this?这样的事情呢?

let isLoading = false;
let controller = new AbortController();

const abort = () => controller.abort();

const button = document.getElementById("test");

const fetchData = () => {
  if (isLoading) {
    abort();
    controller = new AbortController();
  }
  
  isLoading = true;
  
  return fetch('https://jsonplaceholder.typicode.com/todos', {
        signal: controller.signal
      })
      .catch(e => {
        console.warn(`Fetch 1 error: ${e.message}`);
      })
      .finally(() => isLoading = false);
}

button.addEventListener('click', () => {
  fetchData();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM