Tip: Abort a fetch request in JavaScript – 30 seconds of code

The Fetch API is nowadays the de facto way to send asynchronous requests in JavaScript. This is in part due to the fact that the fetch() method accepts a multitude of useful options. One of these is the signal option, which can be used to abort a request. To create a valid value for this option, you can use AbortController.signal after creating a new instance of AbortController. Then, you can use AbortController.abort() to cancel the request at any time.

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

fetch('https://my.site.com/data',  signal ).then(res => console.log(res));


This is particularly useful in scenarios where a request takes too long or the response is no longer needed. You can see a common React use-case for this in the useFetch hook.

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets

  • Messing up the order of chained then and catch methods in JavaScript promises can result in all sorts of problems. Here’s a short primer on the subject.

  • Performs left-to-right function composition for asynchronous functions.

  • Converges a list of branching functions into a single function and returns the result.

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

Manam Volcano Volcanic Ash Advisory: CONTINUOUS VA OBS TO FL080 EXT SW AT 15/0820Z to 8000 ft (2400 m)

Next Article

Alexander-Arnold celebrates 'unreal' FA Cup win as Liverpool star completes the set

Related Posts