DEV Community

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

Posted on

2 1

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 🦄

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay