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 🦄

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)