DEV Community

Cover image for To fetch or not to fetch? That should be an option.
Bernard Baker
Bernard Baker

Posted on

To fetch or not to fetch? That should be an option.

Here's a use case which is part of many UX designs.

Use case: Cancel a download.

Use case description: The title of this use case is simply an analogy for a process which uses fetch and a process which can be cancelled using the AbortController.

Let us define the abort controller

The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired. You can create a new AbortController object using the AbortController. ... Communicating with a DOM request is done using an AbortSignal object.

And a code example which can be copied into the console and executed.

// declare the variables and a dummy URI
let controller, signal, url = "https://raw.githubusercontent.com/BuzzFeedNews/nics-firearm-background-checks/master/data/nics-firearm-background-checks.csv";

// initialise the abort controller and store a signal
controller = new AbortController();
signal = controller.signal;

// a form upload function
const download = async () => {
    let data, response;
    try {
      data = await fetch(url, {signal});
      response = await data.text();
      console.log(response);
    } catch(e) {
      console.log(e);
    }
}

setTimeout( () => {
    controller.abort();
}, 500);

download();

Enter fullscreen mode Exit fullscreen mode

So there you have it. Downloads can now be cancelled 🦄

Top comments (0)