Is there a way to cancel a fetch request and initiate a new one right away?

Below is an illustration taken from MDN. The example showcases two buttons - one for sending a request and the other for canceling it.


var controller = new AbortController();
var signal = controller.signal;

var downloadBtn = document.querySelector('.download');
var abortBtn = document.querySelector('.abort');

downloadBtn.addEventListener('click', fetchVideo);

abortBtn.addEventListener('click', function() {
  controller.abort();
  console.log('Download aborted');
});

function fetchVideo() {
  ...
  fetch(url, {signal}).then(function(response) {
    ...
  }).catch(function(e) {
    reports.textContent = 'Download error: ' + e.message;
  })
}

In my scenario, there's a unique factor of having a query parameter. If a fetch operation is ongoing but not yet completed, and there's a change in the query parameter - how can I automatically send a new request while canceling the previous one?

Answer №1

It seems like there may be some confusion, but as far as I understand, your situation is not unique.

The key principles remain consistent - store the controller in a location that can be accessed by your logic to potentially cancel it if necessary before initiating a new request:

let aborter = null; // ensuring accessibility to aborter
function fetchData(parameter) {
  // check for any pending request and cancel if needed
  if(aborter) aborter.abort();
  // make the request cancellable
  aborter = new AbortController();
  const signal = aborter.signal;
  const url = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png?rand=' + parameter;
  return fetch(url, {signal})
  // cleaning up, although not essential, can provide clarity on pending requests
  .then(response => {aborter = null; return response;})
}
// first request will be cancelled
fetchData("foo")
  .then(response => console.log('foo done'))
  .catch(error => console.error('foo failed', error.name, error.message));
// second request will cancel the previous one
fetchData("bar")
  .then(response =>  console.log('bar done'))
  .catch(error => console.error('bar failed', error.name, error.message))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulties with Grid Layout in React Material Design UI

I've been working on a project and I'm using the Material UI Grid Component to create a specific layout, but no matter what I do, I just can't seem to get it right. The layout I'm aiming for in my Dialog looks like this: https://i.sst ...

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

Condition has been fulfilled for both ngShow and ngHide

I am attempting to show a loading icon while data is being loaded, and then display the data once it is ready. However, I am encountering a problem where for a brief moment, both the loading icon and the data are visible... https://i.sstatic.net/vDXOG.png ...

Monitor the DOM for visibility changes in Selenium WebDriver and PjantomJS before proceeding

I am currently creating automated test scripts using selenium-webdriver, phantomJS, and mocha. The script file I'm working with is a JavaScript file. My goal is to wait until an element (<a>) is fully visible before clicking on it. Let me pro ...

The second asynchronous function relies on the completion of the first

Despite dedicating two days to exploring async/await and promises, I am still unable to make it work correctly. The challenge lies in the fact that the second await for b relies on the result of the first a. It seems no matter what approach I take, b keep ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

Could someone kindly clarify the workings of this jQuery script for me?

I found this code online, but I'm struggling to comprehend its functionality. In order to make any edits for my needs, I need to understand how it operates. The purpose of this script is to close a panel with an upward slide animation when the "x" but ...

Tips for using conditional rendering with React and TypeScript

Issue with Conditional Rendering in TypeScript It seems like I might have encountered a problem with the way I declare my components. Take a look at this TypeScript snippet: import React, { FunctionComponent } from 'react'; export const Chapte ...

How do I reduce the size of a WinJS image file

Can anyone help me figure out how to retrieve the size (in pixels, bytes) of a picture in a Windows 8 app? I'm using openPicker to select the file but can't seem to find the size attributes. I want to display an error message if the file is too ...

Hold off until the script is successfully downloaded and executed, then patiently wait for the DOM to finish loading

I'm facing a challenge with running Javascript conditionally without it being in requirejs form. The script is located on the same server/domain as the requesting page, where an ajax call needs to be made. Is there a foolproof way to ensure that an a ...

What are the steps for skipping, sorting, and limiting with dynamoose?

After being familiar with MongoDB and mongoose, I am now exploring dynamoose for my app. In order to replicate the below-shown mongoose query using dynamoose, how can I write it? Specifically, I want to achieve the same functionality as the following mong ...

I desire to alter the description of an item within a separate div, specifically in a bootstrap

I used the map method to render all the images. However, I need a way to track the current image index so that I can change the item description located in another div. Alternatively, if you have any other solutions, please let me know. App.js : import Ca ...

Unable to fetch css file in Node.js

I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly. Let me share the relevant ...

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...

Looking to transform a list into JSON format using JavaScript?

I have a collection that looks like this: <ol class="BasketballPlayers"> <li id="1">Player: LeBron, TotalPoints: 28753, MVP: true</li> <li id="2">Player: Steph, TotalPoints: 17670, MVP: true< ...

Can you notify all channels when the discord bot experiences a crash?

Is there a way to have my discord bot send a message in a specific channel when it crashes, similar to what I've seen with other bots? ...

Generating HTML table rows dynamically in Angular based on the number of items stored in a $scope variable

In my current project, I am utilizing Angular to dynamically populate data in an HTML table. Instead of manually coding each row for display, I am in need of a solution that allows me to programmatically define each HTML row. The Angular controller snippet ...

Beginning a counter: a step-by-step guide

I am currently utilizing Angular to create a functional counter like so: <button ng-click="order.startOperation(operation)"> <p ng-if="counter.start"></p> </button> When the button is clicked, it triggers a function that initia ...

Dealing with Regular Expressions in Javascript and PHP Challenge

I am struggling to achieve the same outcome with my JavaScript as I do with my PHP code. The issue lies in how JavaScript omits backslashes, unlike PHP. To address this, I have included random forward and backward slashes to cater for different systems. Se ...

Mastering the art of smooth transitions between three animation sequence states using three.js in the animate loop

I want to achieve smooth transitions for the three different wing flapping sequences within a short period of time. Currently, the transitions appear abrupt as they jump from one state to another. The wings have 3 distinct states: 1) On the ground, 2) Flyi ...