myHotTake

Tag: abortcontroller example

  • How to Cancel Fetch Requests with AbortController in JS

    If you enjoy this story, feel free to like or share it with your friends!


    I’m on a camping trip in the wilderness, and my task is to send out a drone to explore the forest and gather information about the terrain. The drone is my trusty Fetch request, flying out to bring back data from the great unknown. But, like any good adventurer, I need to be prepared to call back my drone if conditions change or if I decide I no longer need that data.

    To do this, I have a special tool: a walkie-talkie, which represents the AbortController. Before launching the drone, I make sure to hand it a receiver, which is akin to the signal from the AbortController. This connection allows me to communicate with the drone while it’s on its mission.

    As the drone soars through the forest, gathering intel on the landscape, I continue monitoring the situation from my campsite. Suddenly, the weather starts to change, and I realize that I need to bring the drone back before it gets caught in a storm. I quickly use my walkie-talkie to send a message to the drone, telling it to abort the mission and return to base.

    In JavaScript terms, this is me calling the abort() method on the AbortController, which sends a signal to the Fetch request to stop what it’s doing. The drone, understanding the urgency of my command, immediately ceases its data collection and returns safely to camp, just like a Fetch request would halt its operation when receiving the abort signal.

    By using the AbortController, I manage to keep control over my exploration, ensuring that I can adapt to changing circumstances and maintain the safety of my drone. In the wilderness of code and data, having this ability is invaluable, allowing me to navigate my adventures with confidence and agility.


    Part 2: Tying Back to JavaScript

    In our story, the walkie-talkie was the key to aborting the drone’s mission. In JavaScript, the AbortController plays a similar role. Here’s how I would set this up in code:

    1. Create an AbortController Instance:
       const controller = new AbortController();
       const signal = controller.signal;

    Here, I create an instance of AbortController. The signal property is like the receiver for my drone, which will listen for any abort signals.

    1. Initiate a Fetch Request with the Signal:
       fetch('https://api.example.com/data', { signal })
         .then(response => response.json())
         .then(data => console.log(data))
         .catch(err => {
           if (err.name === 'AbortError') {
             console.log('Fetch aborted');
           } else {
             console.error('Fetch error:', err);
           }
         });

    In this code, I initiate a Fetch request, passing the signal as part of the options. This tells the Fetch request to listen for abort signals.

    1. Abort the Fetch Request:
       // Simulate a condition where I need to abort the fetch request
       setTimeout(() => {
         controller.abort();
       }, 5000);  // Abort after 5 seconds

    Here, I simulate a condition where the Fetch request needs to be aborted. After 5 seconds, I call controller.abort(), which sends an abort signal to the Fetch request, just like I used the walkie-talkie to call back the drone.

    Key Takeaways

    • AbortController: This API provides a way to abort one or more web requests as needed. It’s especially useful in scenarios where requests need to be canceled based on user actions or other conditions.
    • Signal Object: The signal, obtained from controller.signal, is passed to the Fetch request. It allows the request to listen for and react to abort signals.
    • Handling Abort: When a Fetch request is aborted, it throws an AbortError. Handling this error allows us to distinguish between an intentional abort and other types of errors.