ArticleZip > How Do I Cancel An Http Fetch Request

How Do I Cancel An Http Fetch Request

When working on web development projects, making HTTP fetch requests is a common task. However, there are times when you might need to cancel an ongoing fetch request. In this article, we will walk you through the steps to cancel an HTTP fetch request in your JavaScript code.

To cancel an HTTP fetch request, you first need to create a controller using the `AbortController` interface, which allows you to abort one or more fetch requests. Here's how you can create an `AbortController` instance:

Javascript

const controller = new AbortController();
const signal = controller.signal;

Once you have created the controller, you can pass the `signal` property of the controller to the `signal` option in the `fetch` function to associate the request with the controller:

Javascript

fetch('https://api.example.com/data', {
  signal: signal
}).then(response => {
  // Process the response
}).catch(error => {
  if (error.name === 'AbortError') {
    console.log('Fetch request was aborted');
  } else {
    console.error('An error occurred', error);
  }
});

To cancel the fetch request, you can call the `abort()` method on the controller instance:

Javascript

controller.abort();

Calling the `abort()` method will signal the fetch request associated with the controller to abort. If the request has not completed by the time `abort()` is called, the `fetch` promise will be rejected with an `AbortError`.

It's important to handle the `AbortError` in your code to gracefully manage the aborted fetch request. You can use a `try-catch` block to catch the `AbortError`:

Javascript

try {
  const response = await fetch('https://api.example.com/data', {
    signal: signal
  });
  // Process the response
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Fetch request was aborted');
  } else {
    console.error('An error occurred', error);
  }
}

By following these steps, you can effectively cancel an HTTP fetch request in your JavaScript code using the `AbortController` interface. This can be useful when you need to cancel ongoing requests due to user actions or other conditions in your application. Remember to handle the `AbortError` to provide a reliable user experience when canceling fetch requests.

×