Cancel Request

Medium

Prompt

Could you explain how to cancel a Fetch API request in JavaScript? I'm looking for an example that demonstrates aborting a Fetch request based on certain conditions or user interactions in my code.

Requirements

  • Make API call using fetch
  • Cancel the API call before you get the response.

Note

You may want to slow down API requests and responses in a browser for testing purposes, such as simulating a slow network connection or for performance testing.

The Chrome DevTools has a Network Throttling feature that you can use to simulate slow network conditions:

  • Open Chrome DevTools (F12 or Right Click > Inspect).
  • Click on the 'Network' tab.
  • You'll see a dropdown that says 'No throttling'. Click on this dropdown.
  • Select one of the preconfigured profiles like 'Slow 3G' or 'Fast 3G'. You can also add custom network profiles by selecting 'Add...' in the dropdown menu.

This method doesn't affect the API itself but simulates the network conditions that might slow down a response.

Hint

Explore using AbortController with the Fetch API to cancel requests. Check out the MDN documentation on Abort Controller for examples on how to implement it.

Solution

Explanation

The script defines a URL pointing to a dog breeds API. Two buttons, 'fetch' and 'cancel', are linked to corresponding elements in the HTML document. When the 'fetch' button is clicked, it triggers a request to the API to retrieve dog breed data.

To manage the fetch operation, the AbortController interface is used, which allows for the cancellation of fetch requests. When the 'fetch' button is clicked, a new AbortController instance is created, and its signal is passed to the fetch request. This signal acts as a communication channel to control the fetch operation.

If the 'cancel' button is clicked while a fetch request is in progress, the script checks if the controller is defined (indicating an ongoing fetch operation). If so, the controller.abort() method is called, which sends a signal to abort the fetch request. This abort action is logged to the console.

The fetch operation itself involves sending a request to the specified URL and handling the response. If the fetch is successful, the response is logged to the console. If an error occurs (such as being aborted or due to network issues), the error is caught and logged.

Note

When abort() is called, the fetch() promise rejects with a DOMException named AbortError.

More about AbortController

00:00

Table of Contents