Here's an example from MDN below. There are two buttons. One is sending a request and another is canceling.
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;
})
}
Now my case is different. I have a query
parameter and if fetching is in progress but not finished and query
parameter changes - how do I send a new request automatically canceling previous one?
Not sure if I got it clearly, but from what I understand, your case is not different no.
The basics are the same, store the controller somewhere accessible to your logic that may cancel it, and cancel it if needed, before sending the new request:
let aborter = null; // make the aborter accessible
function getData(param) {
// cancel pending request if any
if(aborter) aborter.abort();
// make our 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=' + param;
return fetch(url, {signal})
// clean up, not really needed but may help to know if there is a pending request
.then(r => {aborter = null; return r;})
}
// first request will get aborted
getData("foo")
.then(r => console.log('foo done'))
.catch(e => console.error('foo failed', e.name, e.message));
// will abort the previous one
getData("bar")
.then(r => console.log('bar done'))
.catch(e => console.error('bar failed', e.name, e.message))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With