I've read about cancelling fetch requests by using AbortController.abort(). Is there a way to start a request again without aborting it after calling this command?
For example, in this demo from MDN, once Cancel download has been clicked, clicking Download video will trigger the fetch again, but immediately abort it.
Is there a way to allow this request again without aborting it? So, in this case, how could you click Download video to begin the download, click Cancel download to cancel the download, and then click Download video again to start the download again? For example, if the user clicked Cancel download on accident...
Even for new methods of making API requests, by accepting a signal property in their request options object, you can abort requests using the abort() method.
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() constructor. Communicating with a DOM request is done using an AbortSignal object.
The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a fetch request) and abort it if required via an AbortController object.
signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (the {signal} below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.
For example, in this demo from MDN, once Cancel download has been clicked, clicking Download video will trigger the fetch again, but immediately abort it.
They fixed the example. After you click Cancel download
you will be able to start a new download and cancel it again, over and over. In order to achieve that the Download button
instantiate a new AbortController every time, so you get a fresh signal to abort every time:
downloadBtn.addEventListener('click', fetchVideo);
function fetchVideo() {
controller = new AbortController;
signal = controller.signal;
// ...
So it's ok to instantiate new AbortControllers for each request that you may wish to cancel.
You just can't reuse or reset an AbortController
or its signal. If you need to reset it you have to create a new AbortController
instance.
I think this is by design. Otherwise it could get messy e.g. if you hand over the controller or signal to some external library and suddenly they could remotely abort and un-abort your internal state by accident.
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